SyntaxError: Cannot use import statement outside a module

SyntaxError: Cannot use import statement outside a module


在这里插入图片描述

(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冲突了

所以 ,同时使用 importrequire 两种模块管理模式的正确方式应该是使用,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 文件中添加如下规则

{
  "presets": [
    ["env", {"targets": {"node": "current"}}]
  ],
  "plugins": [
    ["@babel/plugin-proposal-decorators", { "legacy": true }]
  ]
}

然后遇到什么奇奇怪怪的问题就在网上使劲 搜索,因为历史总是如此相似。

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值