Visual Studio Code 使用babel設置

要使用es6,須要經過babel將es6轉成es5的代碼,才能在瀏覽器上運行。爲了設置babel,在網上找了不少教程,最後參考了兩篇文章,摸索着成功了。javascript

參考這兩篇文章:java

基於vscode的node的ES2015(ES6)運行環境搭建 - 冬瓜貓的專欄 - CSDN博客node

ES6開發環境配置 - chhpt的博客 - CSDN博客es6

具體設置步驟:npm

一、全局安裝babel-clijson

cnpm install -g babel-cli瀏覽器

二、安裝babel插件babel

cnpm install --save-dev babel-preset-envui

三、項目根目錄下新建.babelrc文件,內容爲es5

{

"presets":["env"],

"plugins":[]

}

四、項目根目錄下新建.vscode文件夾,在裏面新建launch.json 裏面內容爲

設置來源於:ES6開發環境配置 - chhpt的博客 - CSDN博客

{
"version": "0.2.0",
"configurations": [
       {
"type": "node",
"request": "launch",
"name": "啓動程序",
"program": "${workspaceRoot}/src/index.js",//須要編譯的文件
"stopOnEntry": false,
"args": [],
"cwd": "${workspaceRoot}",
//此處的"babelWatch"要和上一步的tasks中的taskName同樣
"preLaunchTask": "babelWatch",
"runtimeExecutable": null,
"runtimeArgs": ["--nolazy"],
"env": {
"NODE_ENV": "development"
           },
"sourceMaps": true,
"outFiles": [
"${workspaceRoot}/dist"//輸出文件的目錄
           ]
       }
   ]
}

五、在.vscode目錄下新建task.json, 內容爲:

{
"version": "0.1.0",
"command": "npm",
"isShellCommand": true,
"showOutput": "always",
"suppressTaskName": true,
"tasks": [{
"taskName": "babelWatch",
//此處第二個參數"babelWatch"要與上一步中的scripts中的編譯腳本的名字同樣
"args": ["run", "babelWatch"],
"isBuildCommand": true
   }]
}

六、在package.json裏增長內容

設置來源於:基於vscode的node的ES2015(ES6)運行環境搭建 - 冬瓜貓的專欄 - CSDN博客

"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"babelBuild": "babel src -d dist/src -s inline", 
"babelWatch":"babel src/**/*.js -d dist -w -s inline"
 },

 

七、編譯運行

命令行終端裏

npm run babelBuild //單次編譯src文件夾裏的js文件到dist/src目錄中

npm run babelWatch //一直監視src文件夾裏js的修改,在保存時編譯到dis/src目錄中

相關文章
相關標籤/搜索