您的位置:首页 > 其它

Visual Studio Code 使用babel设置

2017-11-06 00:00 381 查看
要使用es6,需要通过babel将es6转成es5的代码,才能在浏览器上运行。为了设置babel,在网上找了很多教程,最后参考了两篇文章,摸索着成功了。

参考这两篇文章:

基于vscode的node的ES2015(ES6)运行环境搭建 - 冬瓜猫的专栏 - CSDN博客

ES6开发环境配置 - chhpt的博客 - CSDN博客

具体设置步骤:

1、全局安装babel-cli

cnpm install -g babel-cli

2、安装babel插件

cnpm install --save-dev babel-preset-env

3、项目根目录下新建.babelrc文件,内容为

{

"presets":["env"],

"plugins":[]

}

4、项目根目录下新建.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"//输出文件的目录
]
}
]
}

5、在.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
}]
}

6、在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"
},


7、编译运行

命令行终端里

npm run babelBuild //单次编译src文件夹里的js文件到dist/src目录中

npm run babelWatch //一直监视src文件夹里js的修改,在保存时编译到dis/src目录中
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: