nodejs require/import导包报错以及解决方法
背景#
最近发现一本nodejs的小册,在学习其中的代码时,发现里面用到了chalk-animation
这个库,在install好这个库后,使用require()
导入时报错
Error [ERR_REQUIRE_ESM]: require() of ES Module E:\...\code\node_modules\chalk-animation\index.js from E:\...\code\案例一.js not supported.
Instead change the require of index.js in E:\...\code\案例一.js to a dynamic import() which is available in all CommonJS modules.
由于这本小册写于多年前,现在这个库最新版已经变成了ESModule
导出了,看到报错信息,貌似已经支持了全部的CommonJS模块使用import
导入,果断改成import导入方式。这时候再来运行代码,控制台又爆出如下错误:
import chalkWorker from 'chalk-animation'
^^^^^^
SyntaxError: Cannot use import statement outside a module
这是由于没有声明包类型导致的
解决方案#
打开package.json
,在其中声明包类型为module
,如下所示
{
"devDependencies": {
"chalk-animation": "^2.0.3"
},
"type": "module"
}
type
还可以设置为commomjs
,这个是默认的(V18.4)。去掉type
字段,默认按commonJS处理
如果文件后后缀
意外事故:两种导入导出方式#
有这么两个文件
//step.js
const pad = '.'
exports.step = (t)=>`|${pad.repeat(t)}>>`
//race.js
const { step } = require("./step.js")
const steps = step(20)
module.exports = { steps }
在设置为module
后,原先js文件中module.exports
的方式就不支持了。会报如下错误
const { step } = require("./step.js")
^
ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension
and 'E:\...\code\package.json' contains "type": "module".
To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
根据报错信息提示,我们可以使用两种方法来修改代码。
- 使用
import
的方式来代替require
//导入的改变
// const { step } = require("./step.js")
import { step } from "./step.js"
//导出也要改变
//exports.step = (t)=>`|${pad.repeat(t)}>>`
export function step(t){ return `|${pad.repeat(t)}>>`}
- 把文件拓展名改为
.cjs
。.mjs
文件总是会被当做ES Modules对待,.cjs
文件总是会当做CommonJS对待。
作者:sq800
出处:https://www.cnblogs.com/sq800/p/16685289.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通