Article directory
1. Construction of webpack project
npm init
Initialize the project and press Enter all the way
│ └─ package.json
webpack与webpack-cli
InstallExcuting an order
npm i webpack webpack-cli -D
│ ├─ package.json
│ ├─ node_modules // webpack-cli创建
- Install the compilation template and configure the entry and exit files
- Install compilation template
npm i html-webpack-plugin
Project structure
│ ├─ build
│ │ ├─ build.js
│ │ └─ index.html
│ ├─ node_modules
│ └─ src
│ ├─ index.js | main.js
│ ├─ index.html // 入口文件
| ├─ package.json
| ├─ webpack.config.js
- Configure
webpack.config.js
new entry fileindex.js
, export filebuild
const path = require('path')
// 模板编译
const HtmlWeabpckPlugin = require("html-webpack-plugin")
module.exports = {
mode: 'development',
devtool: false, // 取消eval且不生成soucremap,代码清晰不转换
entry: './src/index.js',
output: {
path: path.resolve(__dirname, './build'),
filename: 'bundle.js',
// 重新打包时, 先将之前打包的文件夹删除掉
clean: true
},
resolve: {
extensions: ['.js', '.json', '.wasm', '.jsx', '.ts']
},
module: {
},
plugins: [
new HtmlWeabpckPlugin({
template: "./index.html"
})
]
}
- Modify package.json packaging command
"scripts": {
"build":"webpack"
},
- Configuration
webpack-dev-server
hot update
Install
npm i webpack-dev-server -D
Revisepackage.json
"scripts": {
"build": "webpack",
"serve": "webpack serve"
},
2. Using babel command line
- Babel itself can be used as an independent tool (like postcss) and can be used alone without being configured with webpack and other build tools.
- If you want to try using babel from the command line, you need to install the library
@babel/core
: The core code of babel, which must be installed;@babel/cli
: allows us to use babel on the command line;
安装 npm install @babel/cli @babel/core
- Use babel to process written ES6 code
src:是源文件的目录;
--out-dir:指定要输出的文件夹dist;
npx babel src --out-dir dist
- implement
npx babel ./src/index.js --out-dir dist
You will find that the code is output to dist
the folder, but it is not downgraded.
上述代码没有降级是因为babel在这里只进行了抽象语法解析
- If you want to downgrade the code, you must use a plug-in
plugin
Install the plugin npm install @babel/plugin-transform-block-scoping -D
- Executing the command
npx babel ./src/index.js --out-dir dist --plugins=@babel/plugin-transform-block-scoping
es6
At this time , the const in the code will be converted to var
3. Babel’s defaults and compiler process
- The above code can convert es6 to es5, but there is too much content to be converted, and it is troublesome to set each one. In this case, you can use the preset
(preset)
- Install
npm install @babel/preset-env -D
- use
npx babel ./src/index.js --out-dir dist --presets=@babel/preset-env
- Transform in code and automatically turn on strict mode
- Babel's underlying principle analysis github analysis
4. Configuration in babel project
4.1 Use of babel-loader and plug-ins
- In actual development, we usually use babel by configuring it in the build tool, such as in webpack.
- Install dependencies
npm install babel-loader @babel/core
- Configure and specify plug-ins in webpack
- Add configuration
module: {
rules: [
{
test: /\.m?js$/,
use: {
loader: "babel-loader",
options:{
plugins: [
"@babel/plugin-transform-block-scoping",
]
}
}
}]
},
4.2 babel-preset
Use
- It is too troublesome to configure it separately in the above code. You can give it directly
webpack提供一个preset
.webpack会根据我们的预设来加载对应的插件列表,并且将其传递给babel
-
Install
npm install @babel/preset-env
plugin
Configuration being modified
rules: [
{
test: /\.m?js$/,
use: {
loader: "babel-loader",
options: {
presets:[
["@babel/preset-env"]
]
}
}
}]
5. Browser compatibility
- Whether or not the code needs to be converted depends on the adapted browser.
bowserlistrc
File parsing
> 0.05% 表示现在使用的游览器市场占有率 (这里默认值是0.5%, 0.1%可兼容谷歌游览器79 )
last 2 versions 表示最近的两个版本
not dead //表示最近24个月浏览器是否进行更新
- Use the command
npx browserslist
to view compatible browsers - Browser market share: share of browsers used
5.1 browserslist tool and writing rules
browserslist工具
Our configured compatibility conditions can be shared under css compatibility and js compatibility
- When a condition is set:
> 1%
; meanscss要兼容市场占有率大于1%的浏览器,js也要兼容市场占有率大于1%的浏览器
;
Browserslist
It is a configuration that shares the target browser and Node.js version between different front-end tools.
- Write rules
- Command line usage
browserslist
npx browserslist ">1%, last 2 version, not dead"
5.2 browserslist configuration
- Can be
package.json
configured in .browserslistrc
Configure in file
> 5%
last 2 versions
not dead
- Conditional relationships between multiple configurations
注意多个游览器兼容配置生效规则
- What you configure here
target
will directly overwritebrowserslistrc
the configuration of the file.
rules: [
{
test: /\.m?js$/,
use: {
loader: "babel-loader",
options: {
presets: [
["@babel/preset-env",{
targets: ">5%"
}]
]
}
}
}]
5.3 Optimize babel’s configuration file
-
The current project is to
babel的配置信息放到一个独立的文件中
use Babel to provide us with two configuration files:babel.config.json
(or .js, .cjs, .mjs) file;babelrc.json
(or .babelrc, .js, .cjs, .mjs) file;
-
What's the difference between the two of them? At present, many projects adopt the multi-package management method.
(babel本身、element-plus、umi等)
.babelrc.json
: More configuration methods were used in the early days, but it is more troublesome to configure the Monorepos project.babel.config.json
(babel7): It can be directly applied to the sub-packages of the Monorepos project, which is more recommended;
json与js的文件配置只是写法不同而已,功能一致
module.exports = {
presets: [
["@babel/preset-env", {
}
]
]
}
6. polyfill
polyfill 其实就是给代码打一个补丁
, can help us use JavaScript better;- Why is polyfill used?
- For example, we use some grammatical features (
例如:Promise, Generator, Symbol等以及实例方法例如Array.prototype.includes等
- But some
浏览器压根不认识这些特性
will inevitably report errors;
- For example, we use some grammatical features (
注意点
Previously babel7.4.0
, it could be used @babel/polyfill的包
, but this package is now deprecated.
babel7.4.0
core-js和regenerator-runtime来
Afterwards, the completed usage can be introduced separatelypolyfill
:
npm install core-js regenerator-runtime --save
- Configuration
babel.config.js
useBuiltIns
: Set how to use polyfill;corejs
: Set the version of corejs. The 3.x version is currently used more often. For example, I use the 3.8.x version;- In addition, corejs can set whether to support features in the proposal phase;
- Just set the proposals attribute to true;
6.1 useBuiltIns attribute setting
- fasle value, no default value is set
- The packaged files do not use polyfill for adaptation; and there is no need to set corejs attributes at this time;
usage
- The required polyfills will be automatically detected based on the language features appearing in the source code; this can ensure that the number of polyfills in the final package is minimized, and the packaged package will be relatively smaller;
- Not set
- set up
- entry
- If a library you want to rely on uses certain polyfill features, but because we are using it
usage
, the user's browser may report an error later; you can use itentry
;
- If a library you want to rely on uses certain polyfill features, but because we are using it
// 入口文件引入
import 'core-js/stable';
import 'regenerator-runtime/runtime';
- Full configuration
module.exports = {
presets: [
["@babel/preset-env", {
// corejs:3,
// useBuiltIns:false // 默认值就是不使用polyfill
// corejs:3,
// useBuiltIns:"usage" //自动检测需要的polyfill, 会把使用string的方法代码全部做个打包
corejs: 3,
useBuiltIns: "entry" // 解决 依赖的某一个库本身使用了某些polyfill的特性
// 需要在入口文件中添加 `import 'core-js/stable'; import 'regenerator-runtime/runtime'
}
]
]
}
- Complete project directory
│ ├─ build
│ │ ├─ build.js
│ │ └─ index.html
| ├─ dist
│ ├─ node_modules
│ └─ src
│ ├─ index.js | main.js
│ ├─ index.html // 入口文件
| ├─ package.json
| ├─ webpack.config.js
| ├─.browserslistrc
| ├─ babel.config.js
Reference article
- coderwhy
- jcat_李小黑
- DevHappy
- github browserslist
- In addition, when the vue2 project is upgraded to the vue3 project for packaging, the build is executed twice.
- project address
7. Babel compiles third-party plug-ins
7.1 react support
Install
npm i react react-dom
- Write
jsx
document
import React, {
memo } from 'react'
const app = memo(() => {
return (
<div>app</div>
)
})
export default app
- Import
react 与react-dom
andrender
mount the pluginApp
注意
to be inindex.html 中创建类或者id标签
import React from 'react';
import ReactDom from 'react-dom/client';
import App from './react/app.jsx';
const Root = ReactDom.createRoot(document.querySelector('.root'))
Root.render(<App />)
-
Configuration
babel-loader
-
Code processing
react jsx
and parsing plug-in: -
But during development, we do not need to install these plug-ins one by one, we can directly use them
preset
to configure
npm install @babel/preset-react -D
module.exports = {
presets: [
["@babel/preset-env"],
["@babel/preset-react"]
]
}
7.2 TS support ts-loader
- Preface We can convert it into JavaScript through the TypeScript compiler:
npm install typescript -D
- In addition, we usually write a
tsconfig.json
file for TypeScript compilation configuration information:
tsc --init // 生成tsconfig.json
- You can run npx tsc to compile your own ts code
- When using TypeScript in webpack, then we can use
ts-loader
to process ts files:
Install npm install ts-loader -D
- Write TS and use
export const sum=(num1:number,num2:number)=>{
return num1+num2
}
- Configure loader and package
{
test: /\.ts$/,
use: {
loader: "ts-loader",}
}
注意
If the following error occurs when packaging, configure ittsconfig.json
- Resolve Step 4 Errors
- implement
tsc --init
- Configuration compatible with es version
7.3 babel’s support for TS
- Configure babel-loader
{
test: /\.ts$/,
use: {
loader: "babel-loader",
}
- Installation
@babel/preset-typescript
and configuration
npm install @babel/preset-typescript -D
module.exports = {
presets: [
["@babel/preset-env"],
["@babel/preset-react"],
["@babel/preset-typescript"]
]
}
ts-loader
andbabel-loader
choice- Use ts-loader (TypeScript Compiler) to directly compile TypeScript, then you can only convert ts into js;
- If we also want to add corresponding syntax (compatible with Promise and includes) in this process
polyfill
, then ts-loader is powerless;- We need to use babel to complete the polyfill filling function;
- Use babel-loader (Babel) to directly compile TypeScript, or convert ts into js, and realize the polyfill function;
["@babel/preset-typescript",{
// corejs:3,
// useBuiltIns:"usage"
}]
- babel-loader will not detect type errors during the compilation process;
- The type of execution
npm run type-check可以对ts代码
is detected; - execute
npm run type-check-watch可以实时的检测类型错误
;
- The type of execution
"ts-check":"tsc --noEmit",
"ts-check-watch":"tsc --noEmit --watch"