babel的官網說babel是下一代的js語法編譯器,如今本身也在不少項目中使用了babel,但是本身對babel的認識呢,只停留在從google和別人項目中copy的配置代碼上,心裏感到很不安,最近花了點時間整理了一下,分享給大夥。javascript
一般在前端或node項目中,進行如下配置:html
// babel require('babel-core/register')({ presets: ['es2015', 'stage-0'] }); require('babel-polyfill'); require('./app.js');
{ "presets": ["es2015", "stage-0"] }
目前babel提供了幾個官方的preset,主要包括:env es2015 es2016 es2017 flow latest react 。設置presets的時候須要提早npm安裝相應的插件,插件名格式:babel-preset-xxx;以下:前端
{ "presets": ["es2015"] } npm install babel-preset-es2015
{ "plugins": ["transform-es2015-classes"] }
module: { loaders: [{ loader: 'babel', test: /\.js/, include: path.join(__dirname, 'src'), query: { plugins: ['transform-runtime'], presets: [ 'es2015', 'stage-0'], }}] }
entry: [ 'babel-polyfill','src/index.js', ], module: { loaders: [{ loader: 'babel', test: /\.js/, include: path.join(__dirname, 'src'), query: { presets: ['es2015', 'stage-0'] }}] }
參考資料: