gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:28:37 25 4
gpt4 key购买 nike

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

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/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com