preface
- Q: Why Babel?
- Webpack only understands ES5 syntax JS files, not ES6+ syntax and js new apis.
- Babel can convert ES6+ syntax and new JS apis into ES5 syntax.
Download Babel and related
-
Yarn add babel-loader @babel/ core@babel /preset-env @babel/plugin-transform-runtime –dev
-
Runtime dependencies: yarn add@babel /runtime-corejs3 core-js@3
File babel.config.js (Babel configuration file)
Create the babel.config.js or.babelrc file in the project root directory
module.exports = {
"presets": [["@babel/preset-env"]],"plugins": [["@babel/plugin-transform-runtime",
{
corejs: {version: 3.proposals: true},
helpers: true.useESModules: true.regenerator: true.absoluteRuntime: "./node_modules"}}]].Copy the code
New API @babel/plugin-transform-runtime: es New feature conversion, and the transformed code is recommended to a common method. Reduce the amount of code, reduce the package size.
Note: Before configuring Babel, you need to configure Browserslist, which we set directly in package.json
"browserslist": [
"1%" >."last 2 versions"."not ie <= 8"
]
Copy the code
Webpack.config.js file (webpack configuration file)
Create the webpack.config.js file in the project root directory
const path = require('path');
module.exports = {
entry: path.resolve(__dirname, 'src'),
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'main.js'
},
module: {
rules: [{test: /\.js$/,
exclude: /(node_modules|bower_components)/,
include: path.resolve(__dirname, 'src'),
use: {
loader: 'babel-loader'}}]}};Copy the code
Exclude: excludes paths include: includes paths
Run the yarn build command to package the file and compare the generated files
- Before using Babel:
- Es6 + syntax exists for arrow functions, const keywords, and so on
- Es6 + syntax exists for arrow functions, const keywords, and so on
- After using Babel:
- ES6+ syntax is converted to ES5 syntax
- ES6+ syntax is converted to ES5 syntax
link
Webpack Basic Configuration (1)