运行nodejs项目报错如下:
$ npm start
> m-mall-admin@1.0.0 start D:\SoftwareAndProgram\program\weixin\miniprogram\mini-mall\mini-mall-admin
> babel-node ./bin/www
(node:4488) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
D:\SoftwareAndProgram\program\weixin\miniprogram\mini-mall\mini-mall-admin\bin\www:4
import app from '../app';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at wrapSafe (internal/modules/cjs/loader.js:1043:16)
at Module._compile (internal/modules/cjs/loader.js:1091:27)
at loader (D:\SoftwareAndProgram\program\weixin\miniprogram\mini-mall\mini-mall-admin\node_modules\babel-register\lib\node.js:146:5)
at Object.require.extensions.<computed> [as .js] (D:\SoftwareAndProgram\program\weixin\miniprogram\mini-mall\mini-mall-admin\node_modules\babel-register\lib\node.js:156:
7)
at Module.load (internal/modules/cjs/loader.js:976:32)
at Function.Module._load (internal/modules/cjs/loader.js:884:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:67:12)
at D:\SoftwareAndProgram\program\weixin\miniprogram\mini-mall\mini-mall-admin\node_modules\babel-cli\lib\_babel-node.js:151:24
at Object.<anonymous> (D:\SoftwareAndProgram\program\weixin\miniprogram\mini-mall\mini-mall-admin\node_modules\babel-cli\lib\_babel-node.js:152:7)
at Module._compile (internal/modules/cjs/loader.js:1121:30)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! m-mall-admin@1.0.0 start: `babel-node ./bin/www`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the m-mall-admin@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\lenovo\AppData\Roaming\npm-cache\_logs\2019-11-29T03_31_13_816Z-debug.log
D:\SoftwareAndProgram\program\weixin\miniprogram\mini-mall\mini-mall-admin (master -> origin) (m-mall-admin@1.0.0)
$ node -v
v13.2.0
D:\SoftwareAndProgram\program\weixin\miniprogram\mini-mall\mini-mall-admin (master -> origin) (m-mall-admin@1.0.0)
$ npm -v
6.13.1
大概意思是nodejs不支持import语法,如果要支持,需要babel来支持。
babel的安装
所以我们来安装babel吧, 有了babel, 能够使用更多高级词法!
在项目根目录下,执行:
npm install --save babel-core
npm install --save babel-preset-env 或者 npm install --save babel-preset-es2015
npm install babel-cli -g
接着在项目根目录下
创建一个名字为.babelrc
的文件, 文件内容入如下( 要注意window系统下创建这种文件系统会提示你:“必须键入文件名” , 你可以找别的方式去创建, 我是在开发工具的工程目录中把这个文件创建出来的,也可以用cmder神器的vim命令
):
{
"presets": [
"es2015"
],
"plugins": []
}
或者:
{
"presets": [
"env"
],
"plugins": []
}
到目前为止babel算是安装完毕了。
接下来可以用npm start
和babel-node app.js
运行项目。
参考
用babel解决nodejs项目import报错,nodejs之使用babel支持es6和pm2下使用babel
作者简洁
作者:小碗汤,一位热爱、认真写作的小伙,目前维护原创公众号:『我的小碗汤』,专注于写go语言、docker、kubernetes、java等开发、运维知识等提升硬实力的文章,期待你的关注。转载说明:务必注明来源(注明:来源于公众号:我的小碗汤,作者:小碗汤)