具体设置步骤
1.全局安装babel-cli
cnpm install -g babel-cli
2.安装babel插件
cnpm install --save-dev babel-preset-env
或者
npm install --save-dev babel-preset-es2015-loose babel-preset-es2015
在项目根目录下执行上面命令,会生成node_modules文件夹和package.json
3.项目根目录下新建.babelrc文件
文件内容:
{
"presets":["env"],
"plugins":[]
}
或者
{
"presets":["es2015-loose"],
"plugins":[]
}
4.项目根目录下新建.vscode文件夹
在该文件夹下新建文件:
launch.json:
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "启动程序",
"program": "${workspaceRoot}/src/index.js",//需要编译的文件
"stopOnEntry": false,
"args": [],
"cwd": "${workspaceRoot}",
"preLaunchTask": "babelWatch",
"runtimeExecutable": null,
"runtimeArgs": ["--nolazy"],
"env": {
"NODE_ENV": "development"
},
"sourceMaps": true,
"outFiles": [
"${workspaceRoot}/dist"//输出文件的目录
]
}
]
}
task.json:
{
"version": "0.1.0",
"command": "npm",
"isShellCommand": true,
"showOutput": "always",
"suppressTaskName": true,
"tasks": [{
"taskName": "babelWatch",
"args": ["run", "babelWatch"],
"isBuildCommand": true
}]
}
5.在package.json里增加内容
新增的内容:
"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"
}
package.json最终的内容:
{
"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"
},
"devDependencies": {
"babel-preset-env": "^1.7.0"
}
}
6.编译运行
在命令行终端里执行
单次编译src文件夹里的js文件到dist/src目录中:
npm run babelBuild
一直监视src文件夹里js的修改,在保存时编译到dis/src目录中:
npm run babelWatch