节点版本:
节点-v
v12.13.0
我阅读了有关在Node.js中使用ES模块的文档:
Node.js将被视为
CommonJS
所有其他形式的输入,例如,.js
最近的父package.json
文件不包含顶级"type"
字段的文件
这是我的package.json
文件:
{
"type": "module",
"name": "sandbox",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node ./src/index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"ramda": "^0.26.1"
}
}
这是我的./src/index.js
:
import R from "ramda";
const src = {name:"Bob",age:7};
const _src = R.clone(src);
console.log(_src);
我尝试通过npm start
或启动我的代码,node ./src/index.js
但出现错误:
从“ ramda”导入R;
^^^^^^SyntaxError:无法在模块外部使用import语句
为什么会发生?即为什么节点会忽略我的"type": "module"
设置?
同时,它可以正常工作:
node --experimental-modules .\src\index.js
在节点12中,您需要运行带有--experimental-modules
标志的节点以启用对ECMAScript模块的支持。
import
是ES6的一部分,默认情况下NodeJS不支持它。它可以通过将import替换为来工作require
。或者,您可以.babelrec
按此处的回答使用。
同样,对于ES模块使用,“ main”的值必须是完整路径,包括扩展名:“ ./ src / index.js”,而不是“ index.js”。
{
"type": "module",
"main": "./src/index.js"
"scripts": {
"start": "node --experimental-modules ./src/index.js"
},
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句