【问题标题】:ES6 (ECMAScript 2015) modules: import index.jsES6 (ECMAScript 2015) 模块:导入 index.js
【发布时间】:2016-09-06 16:07:06
【问题描述】:

在 Internet 上查找我对特殊的“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


    【解决方案1】:

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

    node --experimental-specifier-resolution=node index
    

    【讨论】:

      【解决方案2】:

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

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


      还是只是“自定义”Node.js/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 部分(当所有浏览器都支持模块时)?

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

      【讨论】:

      • 太棒了!谢谢,很高兴知道这一点
      猜你喜欢
      • 2020-12-20
      • 1970-01-01
      • 1970-01-01
      • 2017-01-04
      • 2017-12-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多