javascript - 在导入 JavaScript 模块时,我们什么时候需要添加文件扩展名?

标签 javascript node.js node-modules

导入模块时,我注意到有时导入的文件有其扩展名,例如:

import { myFunc } from './foo.js';
而其他库,导入不会:
import { myFunc } from './foo';
这与 ES 模块和 CommonJS 模块有关吗?

最佳答案

这取决于您的运行时和编译环境,以及您使用的是 ES 模块(import 语法)还是 CommonJS 模块(require 语法)。在下面找到有关最常见情况的概述:

  • Webpack(由 Create React App 和其他工具使用)与 ES 模块一起使用,如下所示:

  • If the path has a file extension, then the file is bundled straightaway. Otherwise, the file extension is resolved using the resolve.extensions option, which tells the resolver which extensions are acceptable for resolution, e.g. .js, .jsx. More on the offical doc.


  • 如果您在 Node.js 或浏览器中使用 ES 模块而无需任何编译步骤:

  • A file extension must be provided when using the import keyword to resolve relative or absolute specifiers... This behavior matches how import behaves in browser environments... More on the official doc.


  • 如果您在 Node.js 中使用 CommonJS 模块:

  • If the exact filename is not found, then Node.js will attempt to load the required filename with the added extensions: .js, .json, and finally .node. More on the official doc.

    关于javascript - 在导入 JavaScript 模块时,我们什么时候需要添加文件扩展名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72491392/

    相关文章:

    node.js - 为什么我的异步等待无法正常工作

    javascript - JavaScript 中 while 循环中的 http 请求

    javascript - 如何在 Mongoose.js 中应用字段类型验证而不会出现 CastError?

    javascript - 如何将包含npm下载的包的网站部署到surge/gh-pages?

    javascript - package.json 脚本无法解析

    javascript - 将按升序排序的日期数组合并为日期范围数组

    javascript - Node 错误 : Cannot use import statement outside a module even though I'm not

    javascript - 正则表达式允许一个字符(不应该)为什么?

    javascript - jQuery UI Droppable,不通过特定 DIV 传播事件

    javascript - 如何在网页中包含 Bower 组件