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 – – – – – – – part 1: [查 看] juejin.cn/post/695439…

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

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

What is the webpack

Webpack is a front-end resource builder, a static module packer

All front-end resource files (JS /json/ CSS /img/less/…) Will be treated as modules; Webpack will carry out static analysis according to module dependencies and generate corresponding static resources (bundles).

00 loader&plugin commonly used

The resource type

loader/plugin

use

css

style-loader || MiniCssExtractPlugin.loader

css-loader

less-loader

Package style resources

css

optimize-css-assets-webpack-plugin

Compress CSS

css

mini-css-extract-plugin

Extract CSS as a separate file

css

postcss-loader

postcss-reset-env

CSS Compatibility

html

html-webpack-plugin

Process HTML, compress HTML

js

eslit

eslint-loader

eslint-config-airbnb-base

eslint-plugin-import

Syntax checking

js

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. Advanced syntax, need to do compatibility processing: load on demand -> core-js

Js compatible processing

js

Mode = “production” UglifyJsPlugin

Compression js

img

url-loader

Processing images

img

html-loader

Process images in HTML

Other resources

file-loader

Process other resources, such as font files

01 The five core concepts of Webpack

  1. Entry: Indicates which file webpack starts packing as the entry point, analyzing and building an internal dependency diagram
  2. Output: Indicates where and how to name the resource bundles output after Webpack is packaged
  3. Loader: Allows Webpack to process non-JS files (CSS, HTML, img, etc.). Webpack can only understand JS (JS, JSON).
  4. Plugins: Plugins can be used to perform a wider range of tasks, from packaging to optimization and compression to redefining variables in the environment
  5. Mode: instructs Webpack to use the configuration of the corresponding mode mode. There are two modes built into Webpack as follows:

options

describe

The characteristics of

development

The value of process.env.node_env is set to development. Rev NamedChunksPlugin and NamedModulesPlugin

An environment that allows code to be debugged and run locally

production

The value of process.env.node_env is set to production. Enable FlagDependencyUsagePlugin FlagIncludeChunksPlugin, ModuleConcatelationPlugin NoEmitOnErrorsPlugin, OccurrenceOrderPlugin, SideEffectsFlagPlugin and UglifyJsPlugin

An environment that allows code to be optimized and live

02 installation

NPM install webpack webpack-cli -g NPM install webpack webpack-cli -d // Dependency during developmentCopy the code

03 early experience

04 Package style resources

./src/main.js

import from './index.css'; // Create a new style resource and import import './index.less'; // If the style resource file is empty and the Webpack configuration does not process less resources, no error will be reported when webpack is executed on the terminalCopy the code

New webpack. Config. Js

/* webpack.config.js webpack configuration file All build tools run on the Node.js platform. Modularity defaults to common.js (es6 for common.js SRC) */ /* loader: 1. Download 2. Use plugins (configure loader). / / const {resolve} = require('path') const HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = {mode: 'development', // webpack configuration entry: './ SRC /main.js', output: {// filename filename: 'main.js', // output path // __dirname nodejs variable, representing the absolute path of the current file directory path: resolve(__dirname, 'dist')}, // Loader configuration module: { rules: [ { test: /\.css/, use: // NPM I style-loader css-loader -d // create style tags, insert style resources from js into the tags. }, {test: /\.less/, use:}, {test: /\.less/, use: ['style-loader', 'css-loader', // NPM I less less-loader -d 'less-loader']}],}, plugins: [],}}Copy the code

When you execute webpack on the terminal, you can see that index.css and index.less are added to the./dist/main.js package

Create a new index.html file under./dist because the HTML resource is not being processed yet; Import the packaged main.js

<! DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Webpack App</title> <meta name="viewport" content="width=device-width, initial-scale=1" /> </head> <body> <script src="main.js"></script> </body> </html>Copy the code

When the browser is opened, you can see that the style effect takes effect, and the CSS and less are inserted as style tags by loader

Package HTML resources

npm i html-webpack-plugin -D

webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin') module.export = { ... plugins: [// function: New HtmlWebpackPlugin() new HtmlWebpackPluign({// copy the file './ SRC /index.html', Template: './ SRC /index.html'})]}Copy the code

Separate new HtmlWebpackPlugin() and new HtmlWebpackPluign({template: ‘./ SRC /index.html’}) execute webpack in terminal respectively, you can see the output./dist/index.html file is different

Pack image resources

Handles img in CSS

index.html

<div class="code"></div>
<div class="vue"></div>
Copy the code

index.less

.code {
  background: url(./code.jpg) //42kb
;
}
.vue {
  background: url(./vue.jpg) //6kb
;
}
Copy the code

An error is reported when webpack is executed on the terminal

ERROR in ./src/code.jpg 1:0 ...
Copy the code

webpack.config.js

npm i url-loader file-loader -D

module.export = { ... Module: {rules: [... {/ / processing image resources test: / \. (JPG | JPG | GIF) $/, / / as long as the use of a loader, loader statement, multiple, with the use loader: 'url-loader', options: {// Image size less than 8KB, will be base64 processing // advantages: reduce the number of requests (reduce server stress) // disadvantages: The size of the image will become larger, after converting to base64 string format, so the large image will not be converted to Base64. The small image will not affect the file request speed. 8 * 1024, // Rename the image // [hash:10] Take the first 10 bits of the hash for the image // [ext] Take the original file extension name: '[hash:10].[ext]', outputPath: Dist /imgs}}...] }}Copy the code

Execute webpack again, you can pack it and the result is an image, code.jpg; Vue.jpg was converted to base64

Process IMG in HTML

index.html

<img src="./vue.jpg" />
Copy the code

Execute the webpack command directly and the result is as follows

<img src="./vue.jpg" />
Copy the code

The code remains unchanged after packaging, and the package result cannot be displayed normally without vue.jpg. Img images in HTML cannot be processed by default because they cannot be parsed

NPM I html-loader -d Adds html-loader processing

webpack.config.js

module.export = { ... Module: {rules: [... {NPM I html-loader -d test: Loader: 'html-loader',}...] /\.html$/, // }}Copy the code

Webpack resources appear

Automatic publicPath is not supported in this browser

Solutions:

Module. exports = {output: {publicPath: ‘./’}}; [object Module] SRC is set to true by default and false by manual setting. Refer to www.jb51.net/article/176… ; Execute the webpack command again, and the result is as follows

dist/index.html

 <img src="/imgs/be82e5eef9.jpg" />
Copy the code

Both index.html and index.less introduced vue.jpg but ended up packaged as a single image

07 Packing other resources (font files)

Download the font file from iconfont in the/SRC /font directory

main.js

// import iconfont style file "./font/iconfont. CSS ";Copy the code

index.html

<span class="iconfont icon-dollar"></span>
Copy the code

webpack.config.js

/ / packaging other resources (except for HTML, CSS, js resources) such as font file {/ / exclude HTML, CSS, js resources) exclude: / \. | | js | HTML, CSS less | JPG) $/, loader: 'file-loader', options: { name: '[hash:10].[ext]' } }Copy the code

Run the webpack command to see the packed font file in the dist directory, and open dist/index.html to see the imported icon take effect

08 configuration devServer

// Development server: for automation (automatically compile, automatically open browser, automatically refresh browser) // Features: // The main problem NPX wants to solve, Is the module http://www.ruanyifeng.com/blog/2019/02/npx.html call project internal installation / / start devserver commands as follows: NPX webpack-dev-server(webpack4) NPX webpack serve(webpack5) https://segmentfault.com/a/1190000006964335?utm_source=tag-newest // npm i webpack-dev-server -D devServer: {contentBase: resolve(__dirname, 'dist'),// gzip compress: true,// port: 3000,// port: open: True // Automatically open browser},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 – – – – – – – part 1: [查 看] juejin.cn/post/695439…

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

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