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

问题描述 投票:0回答:2

在互联网上查找时,我对特殊的“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
部分(当所有浏览器都支持模块时)?

javascript node.js ecmascript-6 es6-module-loader es6-modules
2个回答
24
投票

ES6 (ECMAScript 2015) 模块官方标准是否支持“index.js”模块解析(指定包含的文件夹)?

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


或者它只是“自定义”Node.js/CommonJS 转译行为?

是的。您可以在文档中阅读有关模块解析算法的信息。相关部分:

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 部分(当所有浏览器都支持模块时)?

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


1
投票

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

node --experimental-specifier-resolution=node index.js

对于使用 Node.js V19+ 的人进行更新,您将需要使用加载器或导入。这是我为解决该问题而开发的库: https://www.npmjs.com/package/specifier-resolution-node

node --import=specifier-resolution-node/register index.js
© www.soinside.com 2019 - 2024. All rights reserved.