(node:24300) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
import fs from 'fs';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at wrapSafe (internal/modules/cjs/loader.js:979:16)
at Module._compile (internal/modules/cjs/loader.js:1027:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
[nodemon] app crashed - waiting for file changes before starting...
如运行node项目时出现如下错误,提示和网上的结果是再package.json 文件里加上"type": "module"
, 因为node 默认是CommonJS
模块管理的, 然后后等你使用了type: module
时,它又出现
require is not defined
node 默认的require
导入格式被type: module
冲突了
所以 ,同时使用 import
和require
两种模块管理模式的正确方式应该是使用,Babel 插件转换
https://www.ruanyifeng.com/blog/2016/01/babel.html 阮一峰老师的博客babel入门教程
在package.json
文件中添加如下依赖
"@babel/core": "^7.19.3",
"@babel/plugin-proposal-decorators": "^7.19.3",
"@babel/register": "^7.18.9",
"babel-preset-env": "^1.7.0",
在.babelrc
文件中添加如下规则文章来源:https://www.toymoban.com/news/detail-531479.html
{
"presets": [
["env", {"targets": {"node": "current"}}]
],
"plugins": [
["@babel/plugin-proposal-decorators", { "legacy": true }]
]
}
然后遇到什么奇奇怪怪的问题就在网上使劲 搜索,因为历史总是如此相似。文章来源地址https://www.toymoban.com/news/detail-531479.html
到了这里,关于SyntaxError: Cannot use import statement outside a module的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!