ES6(EcmaScript 2015)模块:import index.js

时间:2016-05-11 10:13:36

标签: javascript node.js ecmascript-6 es6-module-loader es6-modules

在互联网上看,我对特殊的“index.js”模块文件感到困惑。

使用babelJS + nodeJS或Browserify / Webpack我可以使用import myLib from "./libs"在“libs”目录中导入“index.js”模块(即省略/index/index.js部分)。

ES6(EcmaScript 2015)模块官方标准支持“index.js”模块解析(指定包含文件夹)吗?或者它只是“自定义”NodeJS / CommonJS转换行为?

是否可以在所有浏览器中省略导入的/index | /index.js部分(当所有浏览器都支持模块时)?

1 个答案:

答案 0 :(得分:18)

  

" index.js" ES6(EcmaScript 2015)模块官方标准支持的模块分辨率(指定包含文件夹)?

没有。 ES2015不包含有关模块加载器或如何解释模块标识符的任何内容。

  

或者只是" custom" NodeJS / CommonJS转换行为?

是。您可以在documentation中阅读有关模块分辨率算法的信息。相关部分:

require(X) from module at path Y
1. If X is a core module,
   a. return the core module
   b. STOP
2. If X begins with './' or '/' or '../'
   a. LOAD_AS_FILE(Y + X)
   b. LOAD_AS_DIRECTORY(Y + X)
3. LOAD_NODE_MODULES(X, dirname(Y))
4. THROW "not found"

[...]

LOAD_AS_DIRECTORY(X)
1. If X/package.json is a file,
   a. Parse X/package.json, and look for "main" field.
   b. let M = X + (json main field)
   c. LOAD_AS_FILE(M)
2. If X/index.js is a file, load X/index.js as JavaScript text.  STOP
3. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP
4. If X/index.node is a file, load X/index.node as binary addon.  STOP
  

是否可以在所有浏览器中省略导入的/index|/index.js部分(当所有浏览器都支持模块时)?

希望浏览器实现的目标是最大程度地兼容现有模块加载器,但目前我们还不知道。也许它与浏览器无关,但与服务器如何解析模块标识符有关。我承认我最近没有跟上发展,所以任何其他见解都非常感激:)