ES6转换为ES5
babel转换
使用babel可以将es6的代码转换为es5
参考:https://blog.csdn.net/qq_31411389/article/details/51958332
1.环境要求
环境中安装了node
2.初始化项目package.json
$ npm init -y
3.安装babel
$ npm i -D babel-preset-env babel-cli
env和es2015的区别
env是es2015的升级版,在没有进行配置的情况下,env等同于es2015,任何情况下都推荐使用env
4.创建并配置.babelrc
创建文件.babelrc,并添加代码
{
"presets": ["env"],
"plugins": []
}
5.全局使用babel
5.1 全局安装babel
$ npm install --global babel-cli
5.2 使用babel
# 转码结果输出到标准输出
$ babel example.js
# 转码结果写入一个文件
# --out-file 或 -o 参数指定输出文件
$ babel example.js --out-file compiled.js
# 或者
$ babel example.js -o compiled.js
# 整个目录转码
# --out-dir 或 -d 参数指定输出目录
$ babel src --out-dir lib
# 或者
$ babel src -d lib
# -s 参数生成source map文件
$ babel src -d lib -s
6.当前项目里使用babel
6.1 修改package.json
//在scripts里添加"build":"babel src -d dist"
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
//...do
"build":"babel src -d dist"//内部代码参考5.2
},
6.2 使用babel
$ npm run build

浙公网安备 33010602011771号