由於瀏覽器的版本和兼容性問題,很多es6,es7的新的方法都不能使用,等到可以使用的時候,可能已經過去了很多年。Babel可以把es6,es7的新代碼編譯成兼容絕大多數的主流瀏覽器的代碼。
本篇文章主要介紹在項目中如何安裝配置和使用babel.
1.在項目下初始化 package.json
$ npm init
2.在項目中安裝babel
$ npm install babel-cli --save-dev
3.安裝babel插件
$ npm install babel-preset-xxxxxx --save-dev
Babel5是默認包含各種轉換插件,Babel6.x相關轉換插件需要下載對應的插件,如果不去安裝這些插件,那么在命令行進行轉換時是不會有任何效果的.下面以安裝es2015舉例
$ npm install babel-preset-es2015 --save-dev
還有其他插件,在對文件進行配置的部分詳細介紹
4.配置文件.babelrc
把所使使用的插件對應的規則加入.babelrc
。
{ "presets": ["es2015"],
"plugins": ["transform-es2015-arrow-functions"]
}
配置presets:
a) es2015:
check-es2015-constants // 檢驗const常量是否被重新賦值
transform-es2015-arrow-functions // 編譯箭頭函數
transform-es2015-block-scoped-functions // 函數聲明在作用域內 transform-es2015-block-scoping // 編譯const和let transform-es2015-classes // 編譯class transform-es2015-computed-properties // 編譯計算對象屬性 transform-es2015-destructuring // 編譯解構賦值 transform-es2015-duplicate-keys // 編譯對象中重復的key,其實是轉換成計算對象屬性 transform-es2015-for-of // 編譯for…of transform-es2015-function-name // 將function.name語義應用於所有的function transform-es2015-literals // 編譯整數(8進制/16進制)和unicode transform-es2015-modules-commonjs // 將modules編譯成commonjs transform-es2015-object-super // 編譯super transform-es2015-parameters // 編譯參數,包括默認參數,不定參數和解構參數 transform-es2015-shorthand-properties // 編譯屬性縮寫 transform-es2015-spread // 編譯展開運算符 transform-es2015-sticky-regex // 正則添加sticky屬性 transform-es2015-template-literals // 編譯模版字符串 transform-es2015-typeof-symbol // 編譯Symbol類型 transform-es2015-unicode-regex // 正則添加unicode模式 transform-regenerator // 編譯generator函數
b) es2016:
transform-exponentiation-operator // 編譯冪運算符
c) es2017:
syntax-trailing-function-commas // function最后一個參數允許使用逗號
transform-async-to-generator // 把async函數轉化成generator函數
d) latest:latest是一個特殊的presets,到目前為止包括了es2015,es2016,es2017的插件。
e) react:加入了flow,jsx等語法.
f) stage-x(stage-0/1/2/3/4):按照JavaScript的提案階段區分的,一共有5個階段。而數字越小,階段越靠后.
配置plugins:
引入需要的插件,以下僅以引入箭頭函數舉例
{ "plugins": ["transform-es2015-arrow-functions"] }
另外babel還支持自定義presets 和 plugins.
完成以上配置就安裝好babel了, 可以使用以下的babel的命令進行編譯了
1.在當前命令行輸出轉換
babel test1.js
2.將轉換后的js輸出到指定文件中(使用 -o 或 --out-file )
babel a.js -o b.js babel a.js --out-file b.js
3.實時監控(使用 -w 或 --watch )
babel a.js -w --out-file b.js babel a.js --watch --out-file b.js
4.編譯文件夾並輸出到文件夾中(使用 -d 或 --out-dir )
babel src -d lib babel src --out-dir lib