step one:
Choose your tool (try CLI)
select webpack
Step two:
npm install --save-dev babel-loader @babel/core
module: { rules: [ { test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" } ] }
npm install @babel/preset-env --save-dev
In order to enable the preset you have to define it in your .babelrc file, like this:
{ "presets": ["@babel/preset-env"] }
如果不想添加.babelrc文件可以在webpack.config.js中直接這樣寫:
{ test: /\.js$/, exclude: /node_modules/, loader: "babel-loader", options: { presets: ["@babel/preset-env"] } }
Step three:
有些低版本的瀏覽器,沒有內置新JavaScript語法,比如說promise、map等等
我們需要借助@babel/polyfill將這些語法添加到瀏覽器https://babeljs.io/docs/en/babel-polyfill
npm install --save @babel/polyfill
If you are using ES6's import syntax in your application's entry point, you should instead import the polyfill at the top of the entry point to ensure the polyfills are loaded first:
import "@babel/polyfill";
如果只想將程序中使用到的新語法添加到瀏覽器,而沒有使用到的新語法不用添加可以這么配置:
{ test: /\.js$/, exclude: /node_modules/, loader: "babel-loader", options: { presets: [["@babel/preset-env", { useBuiltIns: 'usage' //如果配置了這個選項 業務代碼里import "@babel/polyfill" 可以不用寫
}]]
}
}
注意:@babel/polyfill還有其它額外的配置下面是示例,詳情請參考: https://babeljs.io/docs/en/usage
Creating a config file named babel.config.json in the root of your project with this content:
{ "presets": [ [ "@babel/preset-env", { "targets": { "edge": "17", "firefox": "60", "chrome": "67", "safari": "11.1", }, "useBuiltIns": "usage", } ] ] }
----------------------------------------------------------------------------------------------------------------------------------------
[以上的配置在寫組件庫或類庫代碼時失效,因為@babel/polyfill是全局注入語法的,污染了全局環境]
所以還有另外一種配置方案:https://babeljs.io/docs/en/babel-plugin-transform-runtime
-----------------------------------------------------------------------------------------------------------------------------------------
