前端的小伙伴們在babel等的加持下,已經可以愉快的使用es6來寫代碼了。
然后對於服務端的nodejs就有點坑爹了,雖然原生支持了es6,但是只是部分支持,一些不支持的特性(比如module)使用了就會報錯,所以如果想使用完整的es6來寫服務端nodejs,我們還是離不開babel。
下面介紹一下在vscode中使用es6寫nodejs的配置方法。
- 首先在根目錄下建立.babelrc文件,寫入babel配置,我的配置如下,記得npm安裝babel及你需要的presets或者plugin。
{ "presets": [ "es2015", "stage-3" ] }
- 其實此時已經可以通過babel-node來執行你的es6代碼了。
babel-node src/index.js
然而這樣的話,vscode里面是無法調試的。所以我們得換個思路,首先將源碼使用babel轉換,然后執行轉換后的代碼,附加一份sourcemap就好了。
- package.json中增加build命令,使用babel轉換es6代碼。
"scripts": { ...... "build": "babel src -d dist --source-maps" }
- 創建一個npm task(vscode概念),用來執行npm run build
{ // See https://go.microsoft.com/fwlink/?LinkId=733558 // for the documentation about the tasks.json format "version": "0.1.0", "command": "npm", //執行npm命令 "isShellCommand": true, "showOutput": "always", "suppressTaskName": true, "tasks": [ { "taskName": "build", //task名稱 "args": [ //npm run build "run", "build" ], "isBuildCommand": true } ] }
該文件在根目錄.vscode目錄下,名字是tasks.json,如果沒有可以自己創建一個。
- 在vscode的調試配置文件中(.vscode -> launch.json),進行如下配置
{ // Use IntelliSense to learn about possible Node.js debug attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "啟動程序", "program": "${workspaceRoot}\\src\\index.js", "sourceMaps": true, //sourcemap打開 "outFiles": [ "${workspaceRoot}\\dist\\index.js" ], //源映射,指定實際執行文件 "preLaunchTask": "build" //首先執行build task }, { "type": "node", "request": "attach", "name": "附加到端口", "address": "localhost", "port": 5858 } ] }
主要干了這幾件事:
- 開啟source-map,以便追蹤到es6源碼
- 運行前先執行build,編譯es6源碼
- 執行和調試編譯后的代碼
OK,現在我們就可以愉快的在vscode里用es6寫nodejs了,撒花~
參考網址:http://stackoverflow.com/questions/38557822/debugging-in-visual-studio-code-with-babel-node