导入模块时,我注意到有时导入的文件有其扩展名,例如:
import { myFunc } from './foo.js';
而其他库,导入不会:import { myFunc } from './foo';
这与 ES 模块和 CommonJS 模块有关吗?
最佳答案
这取决于您的运行时和编译环境,以及您使用的是 ES 模块(import
语法)还是 CommonJS 模块(require
语法)。在下面找到有关最常见情况的概述:
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.
A file extension must be provided when using the
import
keyword to resolve relative or absolute specifiers... This behavior matches howimport
behaves in browser environments... More on the official doc.
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/