Babel 6 特性总结

2019-04-25 14:23:06 浏览数 (1)

0. 改进

  • 模块化
  • 可选的插件
  • 预设
  • 性能改进
  • 插件 API
代码语言:javascript复制
// 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
代码语言:javascript复制
 //index.js
console.log('Hello World!');
代码语言:javascript复制
//register.js
require("babel-register");
require("./index.js");
代码语言:javascript复制
node register.js

注:生产环境不适用

  • babel-node
代码语言:javascript复制
{
  "scripts": {
    //"script-name": "node index.js"
    "script-name": "babel-node index.js"
  }
}

command:

  • --presets
  • --plugins
  • --ignore

注:生产环境不适用

  • babel-core
代码语言:javascript复制
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)
代码语言:javascript复制
    {
    "presets": [
      "es2015",
      "react",
      "stage-2"
    ],
    "plugins": []
  }
  • plugins
    • babel-plugin-transform-es2015-classes
    • babel-plugin-transform-es2015-arrow-functions
代码语言:javascript复制
{
    "plugins": [
      "transform-es2015-classes",
      "transform-es2015-arrow-functions"
    ]
  }
 
代码语言:javascript复制
{
    "plugins": [
      //"transform-es2015-classes"
      ["transform-es2015-classes", { "loose": true }]
    ]
  }

扩展—— Babel 6 loose

  • 基于环境自定义 Babel
代码语言:javascript复制
 {
    "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

0 人点赞