babel筆記
.babelrc配置文件
{
"presets": [],
"plugins": []
}
- presets字段設定轉碼規則
# 最新轉碼規則 $ npm install --save-dev babel-preset-latest # react 轉碼規則 $ npm install --save-dev babel-preset-react
- plugins字段設定babel的插件
# 單獨引入箭頭函數 "plugins": ["transform-es2015-arrow-functions"]
babel-core的作用
- 以編程的方式來使用Babel,如果某些代碼需要調用Babel的API進行轉碼,就要使用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 }
babel-cli的作用
- babel-cli工具用于命令行轉碼。
# 轉碼結果輸出到標準輸出 $ babel example.js # 轉碼結果寫入一個文件 # --out-file 或 -o 參數指定輸出文件 $ babel example.js --out-file compiled.js
babel-loader的作用
- babel加載器,在webpack中想使用babel就需要使用babel-loader,babel-loader會根據.babelrc配置來會用不同的babel(如babel-preset-es2015,babel-preset-react,babel-preset-stage-0之類)
//... { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' } //...
babel-preset-es2015的作用
- babel-preset-es2015中包含了es6->es5所有
//... { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' } //...
babel-polyfill的作用
- Babel默認只轉換新的JavaScript句法(syntax),而不轉換新的API,比如Iterator、Generator、Set、Maps、Proxy、Reflect、Symbol、Promise等全局對象,以及一些定義在全局對象上的方法(比如Object.assign)都不會轉碼。
- $ npm install --save babel-polyfill
//腳本頭部引入: import 'babel-polyfill';// 或者require('babel-polyfill');