Babel is compatible with lower version browsers

1. Construction of webpack project

  1. npm initInitialize the project and press Enter all the way
│  └─ package.json
  1. webpack与webpack-cliInstall

    Excuting an ordernpm i webpack webpack-cli -D

│  ├─ package.json
│  ├─ node_modules // webpack-cli创建
  1. Install the compilation template and configure the entry and exit files
  1. Install compilation templatenpm 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.jsnew entry file index.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"
  },
  1. Configuration webpack-dev-serverhot update

Installnpm 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
  1. Use babel to process written ES6 code
   src:是源文件的目录;
   --out-dir:指定要输出的文件夹dist;
   npx babel src --out-dir dist
  • implementnpx babel ./src/index.js --out-dir dist

You will find that the code is output to distthe folder, but it is not downgraded.

Insert image description here

  • 上述代码没有降级是因为babel在这里只进行了抽象语法解析
  • If you want to downgrade the code, you must use a plug-inplugin

Install the plugin npm install @babel/plugin-transform-block-scoping -D

  • Executing the commandnpx babel ./src/index.js --out-dir dist --plugins=@babel/plugin-transform-block-scoping
  • es6At this time , the const in the code will be converted to var
    Insert image description here

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)
  1. Installnpm install @babel/preset-env -D
  2. usenpx babel ./src/index.js --out-dir dist --presets=@babel/preset-env
  • Transform in code and automatically turn on strict mode
    Insert image description here

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.
  1. Install dependenciesnpm install babel-loader @babel/core
  2. 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",
						]
					}
				}
			}]
	},

Insert image description here

4.2 babel-presetUse

  • It is too troublesome to configure it separately in the above code. You can give it directly webpack提供一个preset.webpack会根据我们的预设来加载对应的插件列表,并且将其传递给babel
  • Installnpm install @babel/preset-env

  • pluginConfiguration 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.
  • bowserlistrcFile parsing
    Insert image description here
> 0.05%   表示现在使用的游览器市场占有率   (这里默认值是0.5%, 0.1%可兼容谷歌游览器79 )
last 2 versions     表示最近的两个版本
not dead     //表示最近24个月浏览器是否进行更新

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%; means css要兼容市场占有率大于1%的浏览器,js也要兼容市场占有率大于1%的浏览器;
  • Write rules
    Insert image description here
    Insert image description here
  • Command line usagebrowserslist

npx browserslist ">1%, last 2 version, not dead"

5.2 browserslist configuration

  1. Can be package.jsonconfigured in
  2. .browserslistrcConfigure in file
> 5%
last 2 versions
not dead

Insert image description here

  • Conditional relationships between multiple configurations
    Insert image description here
  • 注意多个游览器兼容配置生效规则
  • What you configure here targetwill directly overwrite browserslistrcthe 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;
      Insert image description here

注意点Previously babel7.4.0, it could be used @babel/polyfill的包, but this package is now deprecated.

  • babel7.4.0core-js和regenerator-runtime来Afterwards, the completed usage can be introduced separately polyfill:

npm install core-js regenerator-runtime --save

  1. Configurationbabel.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

  1. 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;
  2. 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
    Insert image description here
  • set up
    Insert image description here
  1. 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 it entry;
// 入口文件引入
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

7. Babel compiles third-party plug-ins

7.1 react support

Installnpm i react react-dom

  • Write jsxdocument
import React, {
    
     memo } from 'react'
const app = memo(() => {
    
    
	return (
		<div>app</div>
	)
})
export default app
  • Import react 与react-domand rendermount 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 />)

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.jsonfile for TypeScript compilation configuration information:
tsc --init     // 生成tsconfig.json
  • You can run npx tsc to compile your own ts code
  1. When using TypeScript in webpack, then we can use ts-loaderto process ts files:

Install npm install ts-loader -D

  1. Write TS and use
export const sum=(num1:number,num2:number)=>{
    
    
     return num1+num2
}
  1. Configure loader and package
{
    
    
	test: /\.ts$/,
	use: {
    
    loader: "ts-loader",}
}
  1. 注意If the following error occurs when packaging, configure ittsconfig.json
    Insert image description here
  2. Resolve Step 4 Errors
  • implementtsc --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-typescriptand configuration

npm install @babel/preset-typescript -D

module.exports = {
    
    
	presets: [
		["@babel/preset-env"],
		["@babel/preset-react"],
		["@babel/preset-typescript"]
	]
}
  • ts-loaderand babel-loaderchoice
    • 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可以实时的检测类型错误;
"ts-check":"tsc --noEmit",
"ts-check-watch":"tsc --noEmit --watch"

Guess you like

Origin blog.csdn.net/weixin_46104934/article/details/131750887