import路径

import {test} from \'./test\';

花括号

import {test} from \'./test\';
import test from \'./test\';

如果有默认导出export default则可以省略花括号,且import的模块名是随意的,如:

// a.js
export default \'test\';


// b.js
import a from \'./a\';
import A from \'./a\';
import myA from \'./a\';

export default导出的模板名,在引用时须加花括号,且引用模块名与导出时的命名必须相同,如:

// a.js
export const a = \'test\';


// b.js
import {a} from \'./a\';
import {A} from \'./a\'; // error
import {myA} from \'./a\'; // error

一个模块中只允许一个默认导出export default,但允许多个命名导出export;

路径

import test from \'test\';
import test from \'./test\';

babel默认会把ES6的模块转化为commonjs规范。

import test from \'X\';
// 等价于
var test = require(\'X\');

查找规则:

  1. 如果X是内置模块,则直接返回该模块。如require(\'http\')

  2. 如果X.//../开头:

    • 根据X所在的父模块,确定X的绝对路径。
    • X当做文件,依次查找下面的文件,如果找到,则直接返回。
      • X
      • X.js
      • X.json
      • X.node
    • X当做目录,依次查找下面的文件,如果找到,则直接返回。
      • X/package.json(查找main字段中的文件,规则同上)
      • X/index.js
      • X/index.json
      • X/index.node
  3. 如果X不带路径:

    • 根据X所在的父模块,确定X可能的安装目录。
    • 依次在每个目录中,将X当成文件名或目录名加载。
  4. \"not found\"

模块格式

CommonJS

同步加载模块,主要用于服务端(node)。

// math.js
exports.add = function(a, b) {
  return a + b;
}


// main.js
var math = require(\'./math\');
math.add(2, 3); // 5

AMD

异步模块定义,用于像RequireJS这样的模块加载器,主要用于浏览器。

// math.js
define(function() {
  var add = function(x, y) {
    return x + y;
  }

  return  {
    add: add
  }
})


// main.js
require([\'math\'], function(math) {
  alert(math.add(1, 1));
})

UMD

(function (root, factory) {
    if (typeof define === \'function\' && define.amd) {
        // AMD. Register as an anonymous module.
        define([], factory);
    } else if (typeof module === \' \' && module.exports) {
        // Node. Does not work with strict CommonJS, but
        // only CommonJS-like environments that support module.exports,
        // like Node.
        module.exports = factory();
    } else {
        // Browser globals (root is window)
        root.returnExports = factory();
  }
}(typeof self !== \'undefined\' ? self : this, function () {

    // Just return a value to define the module export.
    // This example returns an  , but the module
    // can return a function as the exported value.
    return {};
}));

ES6

es6通过import、export实现模块的输入输出

参考资料

when-should-i-use-curly-braces-for-es6-import

what require.resolve() does

UMD

收藏 打印