Have synchronous language finch: www.yuque.com/go/doc/5319…

Github:www.yuque.com/go/doc/5319…

This series is an introduction to Webpack and includes:

1, Webpack – 【 introduction – first part 】juejin.cn/post/695439…

2, Webpack — 【 introduction 】【 this article 】juejin.cn/post/695438…

3, Webpack – [Introduction – part 2] juejin.cn/post/695438…

09 Construction Environment Introduction

This is the configuration of the development environment. Mode: ‘development’

Production environment also need to consider:

  1. CSS files are extracted from JS files: the development environment packages the results, font files and images are packaged into separate files, and the directory is determined by options.outputName
  2. CSS and less style files are processed by CSS-Loader and loaded into the common.js module into JS, which will cause js files to be very large and slow to load, and styles need to be processed by style-loader and inserted into HTML. The blinking screen may appear on the page
  3. Code is compressed uniformly
  4. Compatibility issues: styles, partial JS, such as styles that need prefixes to work in older browsers

10 Extract CSS into a separate file (mini-CSS-extract-Plugin)

npm i mini-css-extract-plugin -D

webpack.config.js

. const MiniCssExtractPlugin = require('mini-css-extract-plugin') module: { rules:[ { test: /\.css/, use: // NPM I style-loader css-loader -d // create style tags, insert style resources from js into the tags. Added to the head / / 'style - loader, / / replace style - loader, extract the CSS into individual files in the js MiniCssExtractPlugin. Loader, / / CSS files into commonjs module loading js, },]}, plugins: [// new MiniCssExtractPlugin() new MiniCssExtractPlugin({filename: 'CSS /index.css' // specify the directory to extract CSS files in dist})]Copy the code

When you execute webpack, you can see that the package generates dist/ CSS /index.css, and the CSS file is imported into dist/index.html

<link href="/main.css" rel="stylesheet" />
Copy the code

Open index.html in your browser and see the following

Styles are introduced via the link tag, without blinking

11 CSS Compatibility (PostCSS)

npm i postcss-loader postcss-preset-env -D

webpack.config.js

. // Set the node environment variable process.env.node_env = "development"; module: { rules:[ { test: /\.css/, use: [MiniCssExtractPlugin. Loader, 'CSS - loader, / * CSS compatibility processing: Postcss --> postCSs-loader plugin: postCSs-preset -env */ / NPM I postCSs-loader postCSs-env -D "postcss-loader", options: { postcssOptions: {// PostCSS plugin // Help PostCSS to find the configuration in package.json browserList, can recognize the environment, through the configuration load specified CSS compatibility style plugins: [ [ "postcss-preset-env" ] ], /* "browserslist": {// development environment --> Set the node environment variable: process.env.node_env = "development" "development": [" Last 1 Chrome version", // Compatible with the latest version of Chrome "last 1 Firefox version", "last 1 Safari version"], // Production environment: Production :["> production", // compatible with 99.8% of browsers "not dead", / / browser compatible with no dead "not op_mini all"] /}} *,,}},],},]}Copy the code

package.json

"browserslist": { "development": [" Last 1 Chrome version", "last 1 Firefox version", "Last 1 Safari version"], "production":[">0.2%", "not dead", "not op_mini all" ] }Copy the code

index.css

body{
    ...
    display: flex;
    backface-visibility: hidden;
}
Copy the code

Execute webpack and you can see that the package generates dist/ CSS /index.css

body{
    ...
    display: flex;
    -webkit-backface-visibility: hidden;
            backface-visibility: hidden;
}
Copy the code

Json: process.env.node_env = “development”;

Execute webpack and you can see that the package generates dist/ CSS /index.css

body{
    ...
    display: -webkit-flex;
    display: flex;
    -webkit-backface-visibility: hidden;
            backface-visibility: hidden;
}
Copy the code

12 compress CSS (optimize – CSS – assets – webpack – the plugin)

npm i optimize-css-assets-webpack-plugin -D

webpack.config.js

const OptimizeCssAssetsWebpackPlugin = require("optimize-css-assets-webpack-plugin"); . Plugins: [... / / CSS/compression/NPM I optimize - CSS - assets - webpack plugin - D new OptimizeCssAssetsWebpackPlugin (),]Copy the code

Dist/CSS /index.css has been compressed. Compare the size of the CSS file before and after compression, from 2.58 KB to 2.34 KB

body{height:100%; width:100%; background-color:red; display:flex; -webkit-backface-visibility:hidden; backface-visibility:hidden}@font-face{font-family:iconfont; src:url(/font/67b199ed6b.eot); src:url(/font/67b199ed6b.eot#iefix) format("embedded-opentype"),url("data:application/x-font-woff2; charset=utf-8; base64,d09GMgABAAAAAASoAAsAAAAACXQAAARcAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHEIGVgCDQAqFYIRbATYCJAMYCw4ABCAFhG0HZhsXCBEVpDmQf ZFg207YPiRFXdMUDu9LHUnXRBC/9pt99+6+GN7EEvxIxxsekjZLEC00qIRMJpOKNS+Bn77T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mxfSi1LEKlbgmaFvhubhlWATSROcC8bgBhwFZIul6gMOAyMmMfQ2nMZ6gM0 GIJyjdOex6cw6oLYypYQPYHm1OnTbMov/yJZmhSjos92hfZ2TBEfphOP7BDHmKBG00sokEztXAHl2HTEPRMFebilyJ9EgS66J38nNqZcsFQSqACyPwBK0c62 ukuVObnn5AxaKS4oqXM+YWYY/sHEV/YAPlQdI1aLmWwMzJiQmg8SWOkBe7QhhojQUBfPKqCcsJXdoj1EgHqpJsq/OlV7V3uAQDRD2BGaWOdz+aEmtOZuy2tE +K/Splp8grL3B3DQUPWoMfWlLI95LwWO5nNAA==") format("woff2"),url(/font/2bb59db229.woff) format("woff"),url(/font/a04a06a7d9.ttf) format("truetype"),url(/font/086b7e8295.svg#iconfont) format("svg")}.iconfont{font-family:iconfont! important; font-size:16px; font-style:normal; -webkit-font-smoothing:antialiased; -moz-osx-font-smoothing:grayscale}.icon-dollar:before{content:"\e6f4"}.icon-history:before{content:"\e6f8"}.icon-arrow-d own:before{content:"\e665"}.icon-arrow-double-right:before{content:"\e666"}.icon-comment:before{content:"\e668"}Copy the code

13 JS syntax check (ESLint, Airbnb)

Unify team code style to ensure code readability

npm i eslint eslint-loader eslint-config-airbnb-base eslint-plugin-import -D

webpack.config.js

Rules: [... {/ * syntax check: eslint - loader eslint check to write their own code, the third party libraries without check Settings check rule: a: in the package. In the json eslintConfig set in the "eslintConfig" : {"extends": "airbnb-base"} Method 2: Create a new root directory. "Airbnb-base"} Rule of recommendation: airbnb Eslint-config-airbnb-base use this eslint-config-airbnb-base Our default export contains all of our ESLint rules, including ECMAScript 6+. It requires eslint and eslint-plugin-import. */ // npm i eslint eslint-loader eslint-config-airbnb-base eslint-plugin-import -D test: /\.js$/, loader: "eslint-loader", exclude: /node_modules/, options: {// automatic fix // fix: true}}]Copy the code

Package. json added field

"eslintConfig": {
  "extends": "airbnb-base"
}
Copy the code

Or create a.eslintrc root directory

{
  "extends": "airbnb-base"
}
Copy the code

When you execute Webpack, you can see an error from the console

/Users/zhengxiuyue/Documents/github-workspace/study-webpack/src/main.js 30:15 error A space is required after ',' Comma-spacing 34:1 Warning Unexpected console statement no-console disk 2 problems (1 error, 1 warning) 1 error and 0 warnings potentially fixable with the `--fix` option.Copy the code

Webpack.config.js configuration is automatically fixed

Options: {// Auto fix: true}Copy the code

In this execution, the js file has been fixed without error code, as shown below

/Users/zhengxiuyue/Documents/github-workspace/study-webpack/src/main.js
  34:1  warning  Unexpected console statement  no-console

✖ 1 problem (0 errors, 1 warning)
Copy the code

If you want to have no warning, you can add eslint-disable-next-line to main.js

14 JS Compatibility Processing (Babel)

Switch to ES5 with browser support

npm i babel-loader @babel/core -D

Conclusion: Combine 1 and 3 to do compatibility processing

  1. Problem: Only basic syntax can be converted, for example, promise advanced syntax cannot be preset
  2. @babel/polyfill NPM I @babel/polyfill -S problem: I only want to solve part of the compatibility problem, but it is too large to introduce all the compatibility code
  3. Core-js NPM I core-js-s

Operation steps:

Internet Explorer displays an error when main.js writes es6 syntax

const add = (x, y) => x + y;

console.log(add(3, 9));
Copy the code

Webpack.config. js, or in. Babelrc babel.config.json

rules: [... {/* js compatibility processing: babel-loader@babel/core@babel /preset-env NPM I babel-loader@babel /core -d 1. Basic JS compatibility processing --> @babel/preset-env NPM I @babel/polyfill NPM i@babel /polyfill -s problem: (preset) only basic syntax can be used, such as promise advanced syntax cannot be used. NPM I core-js-s NPM I core-js-s NPM I core-js-s I core-js-s /\.js$/, exclude: /node_modules/, loader: 'babel-loader', options: {// Or configure // preset in. Babelrc babel.config.json to specify Babel to do such compatibility presets: [['@babel/preset-env', {// Load useBuiltIns as needed: Targets: {Chrome: '60', Firefox: '60', IE: '9', safari: '10', edge: '17', }, }, ], ], }, }, ]Copy the code

After executing webpack, you can see the packaged main.js

Const becomes var, arrow function becomes normal function, ie executes normally

eval("var add = function add(x, y) {\n return x + y; \n}; \n\nconsole.log(add(3, 9)); \n\n//# sourceURL=webpack://study-webpack/./src/main.js?" );Copy the code

Main.js writes promise to IE because **@babel/preset-env** can’t handle advanced syntax

Const promise = new promise ((resolve) => {setTimeout(() => {console.log(' timer finished ~ ')); resolve(); }, 1000); }); console.log(promise);Copy the code

Introduce @babel/polyfill and say in main.js

import '@babel/polyfill';
Copy the code

When webpack is executed, Internet Explorer can execute it normally, but the packaged main.js file introduces all advanced syntax processing of JS, as shown in the following figure, resulting in a large volume of the packaged main.js file

Compress HTML and JS

Compression js

Set mode to production

Mode ="production" // Compressed JS, the production environment automatically compressed JS code, will enable the built-in UglifyJsPluginCopy the code

Compressed HTML

HtmlWebpackPlugin configures the minify parameter

Plugins: [new HtmlWebpackPlugin({// copy the file './ SRC /index.html' and automatically import all the resources (js/ CSS) in the package output template: './ SRC /index.html', // compress HTML minify: {// collapseWhitespace: true, // remove comment removeComments: true,},}),],Copy the code

When you execute Webpack, you can see that the packed HTML is compressed and has no comments

16 Review: Basic configuration of the production environment

const path = require('path'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); Const commonCssLoader = [MiniCssExtractPlugin loader, 'CSS - lodaer' {/ / in the package. The jso configuration browserslist loader: 'postcss-loader', options: { postcssOptions: { plugins: [['postcss-preset-env']], }, }, }, ]; module.exports = { mode: 'production', entry: './src/main.js', output: { filename: 'main.js', path: path.join(__dirname, 'dist'), }, module: { rules: [ { test: /\.css$/, use: [...commonCssLoader], }, { test: /\.less$/, use: [...commonCssLoader, 'less-lodaer'],}, // Normally, a file can only be processed by one loader, so be sure to specify the sequence in which loader executes // eslint before executing Babel {test: /\.js$/, exclude: /node_modules/, loader: 'eslint-loader', enforce: 'pre', // To specify the sequence, run options: {fix: true, }, }, { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', options: { presets: [ [ '@babel/preset-env', { useBulitIns: 'usage', corejs: { version: 3, }, targets: { chrome: '60', firefox: '60', ie: '9', safari: '10', edge: '17', }, }, ], ], }, }, { test: /\.(jpg|png|gif)/, loader: 'url-loader', options: { limit: 8 * 1024, name: '[hash:10].[ext]', outputPath: 'imgs', esModule: },}, {test: /\.html/, loader: 'HTML - loader', / / handle your img HTML}, {exclude: / \. (js | | CSS less | | HTML JPG | PNG | GIF) /, loader: 'file - lodaer', the options: { outputPath: 'media', }, }, ], }, plugins: [ new MiniCssExtractPlugin({ filename: 'css/main.css', }), new OptimizeCssAssetsWebpackPlugin(), new HtmlWebpackPlugin({ template: './src/index.html', minify: { collapseWhitespace: true, removeComments: true, }, }), ], };Copy the code

Have synchronous language finch: www.yuque.com/go/doc/5319…

Github:www.yuque.com/go/doc/5319…

This series is an introduction to Webpack and includes:

1, Webpack – 【 introduction – first part 】juejin.cn/post/695439…

2, Webpack — 【 introduction 】【 this article 】juejin.cn/post/695438…

3, Webpack – [Introduction – part 2] juejin.cn/post/695438…