ES6(ECMAScript 2015)模块:导入index.js

ES6 (ECMAScript 2015) modules: import index.js

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

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

ES6(ECMAScript 2015)模块官方标准是否支持“index.js”模块解析(指定包含文件夹)?还是只是“自定义”Node.js /CommonJS 转译行为?

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

Is the "index.js" module resolution (specifying the containing folder) supported by the ES6 (ECMAScript 2015) modules official standard?

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


Or is it just "custom" Node.js/CommonJS transpiling behaviour?

是的。您可以在 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

Will it be possible to omit the /index|/index.js part of the import in all browsers as well (when modules will be supported on all browsers)?

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

Node.js 团队正在研究解决方法:https://nodejs.org/api/esm.html#esm_customizing_esm_specifier_resolution_algorithm

node --experimental-specifier-resolution=node index