我正在做一个节点项目(截图)。我在 helpers.js 中有一个函数(url),我在底部将其导出为:
module.exports = {
urls: urls,
};
在我的 index.js 中,我试图将其导入:
import { urls } from './helpers';
const myUrls = urls(1,3);
当我运行它时,我得到
Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/home/optionhomes11/nodeprojects/hayes/helpers' imported from /home/optionhomes11/nodeprojects/hayes/index.js Did you mean to import ../helpers.js?
我究竟做错了什么?
原文由 user1592380 发布,翻译遵循 CC BY-SA 4.0 许可协议
当您使用 ECMAScript 模块时,您必须提供文件扩展名: https ://nodejs.org/api/esm.html#esm_mandatory_file_extensions
因此,除了其他建议使用
"type": "module"
在 package.json 上,您还需要指定文件扩展名import {urls} from './helpers.js'
。您还可以使用标志--es-module-specifier-resolution=node
使其将 js 文件解析为模块,就像之前使用require