【问题标题】:Getting error "Cannot find module" when using import with Node.js 14.1.0使用 Node.js 14.1.0 导入时出现错误“找不到模块”
【发布时间】:2020-08-18 17:53:44
【问题描述】:

当尝试像这样导入时:

import { port } from './config';

我收到此错误:

错误 [ERR_MODULE_NOT_FOUND]:找不到模块 '/Users/USER/PROJECT/src/config'

但是当我尝试这个导入时它工作正常:

import { port } from './config.js';

config.js 的内容:

export const port = 3000;
export const hostname = localhost;

“type”在我的 package.json 中设置为“module”,使用 Node.js v14.1.0

那么,我该如何使用无扩展导入?

【问题讨论】:

    标签: node.js ecmascript-6 import es6-modules


    【解决方案1】:

    编辑:

    默认使用此标志运行节点

    node --experimental-specifier-resolution=node index.js
    

    在 config.js 的最后,像这样导出你的模块:

     module.exports = { port, hostname };
    

    【讨论】:

    • 嗨,感谢您的回答,但我的问题是如何将无扩展名导入与导入/导出一起使用,而不是 require/module.exports。
    • 对不起,我误会了你。你能发布你的 package.json 文件吗?我复制了一个类似的环境,结果很适合您的节点版本。你的意思是 import { port } from 'config' 吗?
    猜你喜欢
    • 2019-12-13
    • 2021-07-04
    • 1970-01-01
    • 2014-06-12
    • 2020-03-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    • 1970-01-01
    相关资源
    最近更新 更多