0. 改进
- 模块化
- 可选的插件
- 预设
- 性能改进
- 插件 API
// Babel 5
export default function ( {Plugin, types: t} ) {
return new Plugin('ast-transform', {
visitor: { ... }
});
}
// Babel 6
export default function ( { types: t} ) {
return {
visitor: { ... }
};
}
1.安装 Babel 6
npm install
- babel-cli
- usage: babel app.js
- command:
- -o --out-file
- -d --out-dir
- -w --watch
- --source-maps
- babel-register
//index.js
console.log('Hello World!');
代码语言:javascript复制//register.js
require("babel-register");
require("./index.js");
代码语言:javascript复制node register.js
注:生产环境不适用
- babel-node
{
"scripts": {
//"script-name": "node index.js"
"script-name": "babel-node index.js"
}
}
command:
- --presets
- --plugins
- --ignore
注:生产环境不适用
- babel-core
var babel = require("babel-core");
babel.transform("code();", options);
// => { code, map, ast }
babel.transformFile("filename.js", options, function(err, result) {
result; // => { code, map, ast }
});
babel.transformFileSync("filename.js", options);
// => { code, map, ast }
2. 配置 Babel 6
代码语言:javascript复制//.babelrc
{
"presets": [],
"plugins": []
}
//or package.json
{
...
"babel":{
"presets": [],
"plugins": []
}
}
- presets
- babel-preset-es2015
- babel-preset-react
- babel-preset-stage-x(x=0,1,2,3)
{
"presets": [
"es2015",
"react",
"stage-2"
],
"plugins": []
}
- plugins
- babel-plugin-transform-es2015-classes
- babel-plugin-transform-es2015-arrow-functions
- …
{
"plugins": [
"transform-es2015-classes",
"transform-es2015-arrow-functions"
]
}
代码语言:javascript复制{
"plugins": [
//"transform-es2015-classes"
["transform-es2015-classes", { "loose": true }]
]
}
扩展—— Babel 6 loose
- 基于环境自定义 Babel
{
"presets": ["es2015"],
"plugins": [],
"env": {
"development": {
"plugins": [...]
},
"production": {
"plugins": [...]
}
}
}
env
: process.env.BABEL_ENV
or process.env.NODE_env
3. Webpack
代码语言:javascript复制//webpack.config.js
var path = require('path');
···
module.exports = {
···
module: {
loaders: [
{
loader: 'babel-loader',
test: path.resolve(__dirname, 'js'),
query: {
presets: ['es2015'],
},
}
]
},
···
};
- tree-shaking