1. 程式人生 > 其它 >執行nodejs專案,npm start啟動專案import報錯,SyntaxError: Cannot use import statement outside a module

執行nodejs專案,npm start啟動專案import報錯,SyntaxError: Cannot use import statement outside a module


$ npm start > [email protected] 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! [email protected] start: `babel-node ./bin/www` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the [email protected] 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) ([email protected]) $ node -v v13.2.0 D:\SoftwareAndProgram\program\weixin\miniprogram\mini-mall\mini-mall-admin (master -> origin) ([email protected]) $ 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執行專案。

  

伺服器