1. What is Webpack?
Sass,less, TS, etc., is a front-end resource builder, a static module packer builder that compiles web resources that are not known by the browser. By referring to the static resources in the project, all the static modules are packaged into one or more bundles and output through loader conversion files. The plugin injects hooks and finally outputs the files composed of multiple modulesCopy the code
2. Webpack 5 cores (webpack.config.js)
A :Entry type: String,array,object
Figure 1. Single entry, package to form a trunk, output a bundle file,trunk name default is main.js entry: "./ SRC /index.js", 2. Array: [". / SRC/index. Js ", the ". / SRC/test. Js "], (3) the object: {index:"./ SRC /index.js", test:"./ SRC /test.js",} If the entry is a string or array, only one Chunk will be generated, and the name of the Chunk will be main. If the entry is an object, there may be multiple chunks. In this case, the name of Chunk is the name of the key in the object key-value pair. Dynamic configuration Entry: / / synchronization function Entry: () = > {return {a: '/ pages/a', b: '/ pages/b',}}; / / entry: asynchronous function () = > {return new Promise ((resolve) = > {resolve ({a: '/ pages/a', b: '/ pages/b',}); }); };Copy the code
B :Output
Path: Specifies the local directory where the output files are stored. The path must be the absolute path of type String. PublicPath: Specifies the URL prefix that is published to online resources. The default is an empty string ", that is, a relative path. Output: {path: path.resolve(__dirname, "dist"), "[name]. Js", / / packaging of the output file after file name The default is the main js publicPath: 'https://cdn.example.com/assets/', } then release to online HTML when introducing JavaScript files you need: < script SRC = "https://cdn.example.com/assets/a_12345678.js" > < / script >Copy the code
C :Loader
Process non-JS files into self-understood files to match packaging conditions. Test, include, and exclude are used to match files to which Loader applies rules. Application rule: Use the use configuration item to apply Loader to the selected file. You can apply only one Loader or a group of Loaders in sequence from back to front, and pass parameters to Loader respectively. Resetting order: The execution order of a group of Loaders is from right to left by default. Use Enforce to place the execution order of one Loader to the first or last. Rules: [{// Hit JavaScript file test: /\.js$/, // convert JavaScript files with babel-loader //? CacheDirectory represents the parameter passed to babel-loader, which is used to cache Babel compilation results to speed up recompilation. ['babel-loader? CacheDirectory '], // only hits js files in SRC to speed up Webpack search include: Path.resolve (__dirname, 'SRC ')}, { /\.scss$/, // Use a set of loaders to process the SCSS file. ['style-loader', 'css-loader', 'sass-loader'], // exclude files in node_modules: Path. resolve(__dirname, 'node_modules'),}, {// Use file-loader to load test for non-text files: / \. (GIF | PNG | jpe? G | eot | woff | the vera.ttf | SVG | PDF) $/, use: [' file - loader '], parser: {/ / more granular configuration which grammar to parse module which is not resolved amd: False, // Disable AMD CommonJS: false, // disable COMMONJS system: false, // disable SystemJS harmony: // Disable ES6 import/export requireInclude: false, // disable require.include requireEnsure: // Disable require.context browserify: false, // disable browserify requireJs: False, // disable requirejs}}, ]} loader css-loader----> CNPM install --save-dev style-loader CSs-loader module:{rules:[{test: Use :['style-loader','css-loader'], // Use :['style-loader','css-loader']} file-loader npm install --save-dev file-loader { test:/.(png|svg|jpg|gif)$/, use:['file-loader'] } sass: sass-loader npm install sass-loader node-sass --save-dev { test:/\.scss$/, Use :['style-loader','css-loader? Minimize ','sass-loader'], // minimize CSS compression} less: less-loader npm install --save-dev less-loader less { test:/\.less$/, use:['style-loader','css-loader','less-loader'], } Babel: babel-loader loader ES6 or later and JSX file NPM install -d babel-loader @babel/ core@babel /preset-env {test: preset to preset /\.(js|jsx)$/i, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: [' @ Babel/preset - env ']}}} : font file - loader and url - loader {test: / \. (woff | woff2 | eot | the vera.ttf | otf) $/, use: [' file - loader]}Copy the code
D :Plugins
Used to perform a wider range of tasks, from packaging optimization and compression, to redefining variables in the environment. [new HtmlPlugin(), // Default template, New HtmlPlugin({title:'webpack test', template:path.join(__dirname, './public/index.html')}),]Copy the code
E :Mode
Development mode production mode Webpack provides a webpack-dev-server tool for us to build a local running environment. CNPM I webpack-dev-server -d webpack.json "scripts": {"test": "echo \"Error: No test specified\" && exit 1", // 1. Webpack-dev-server --open --port 3000 Change default port 8080 to 3000 and automatically open page // 2. Webpack-dev-server --open --port 3000 --hot // 3 --profile" start": "webpack-dev-server --open --port 3000 --hot --profile", "Webpack-dev-server ", "build": "webpack" // pack} In the development environment, use the command: NPM run start or NPM run dev production environment to pack the operation: NPM run buildCopy the code
F: use DevServer
Provide HTTP services instead of using local file previews; Monitor the changes of files and automatically refresh the web page to achieve real-time preview; Source Map is supported for easy debugging. Configure devServer in webpack.config.js :{contentBase: 'dist', // file lookup open:true, // whether to automatically open port:4396, HotOnly :true,// Only hot updates are used to update the page, the page is not automatically refreshed to update. // SourceMap can cause performance impact. // Devtool :'source-map', // help to locate errors} "^ 3.2.0 webpack", ""," ^ 4.41.2 ", "webpack - cli" : "^ 3.3.12", "webpack - dev - server" : "^ 3.11.2"Copy the code
G: the Chunk:
Code block: A Chunk is composed of multiple modules for code merging and splitting.Copy the code
Webpack related issues
1. How is Webpack different from Grunt and gulp?
Grunt and Gulp were popular in the early days. Webpack is relatively mainstream now, but gulp is still used for some lightweight tasks, such as packaging CSS files separately. Grunt and gulp are based on tasks and streams (tasks, streams). Similar to jQuery, find a file (or a class of files) and do a series of chain operations on it to update the data on the stream. The chain operations constitute a single task, and multiple tasks constitute the entire Web build process. Webpack is portal based. Webpack will automatically recursively parse all the resource files that need to be loaded by the entry, then use different loaders to process different files, and use Plugin to extend WebPack functionality.Copy the code
2. What are common Loaders? What problems do they solve? * * *
A :file-loader: outputs a file to a folder and references the output file through a relative URL in the code b:url-loader: similar to file-loader. C :source-map-loader: load additional source map file, which is easy to debug d:image-loader: E :babel-loader: convert ES6 to ES5 F: CSS-loader: load CSS, support modularization, compression, file import, etc. G :style-loader: inject CSS code into JS. H: ESlint-loader: checks js code through ESLintCopy the code
3. The difference between Loader and plugin?
Loader: Webpack can only parse JS files. Loader is required to parse non-JS files into files recognized by WebPack. In module.rules, the type is array, each item is object, which describes the type of file (test), what to use (loader) and the use of parameters (options) Plugin: Plugins, which extend the functionality of WebPack and make WebPack more flexible, are configured separately in: plugins, which are arrays of types. Each item is an instance of the plugin, and the parameters are passed in through the constructor.Copy the code
4. What is the webpack build process? The process from reading configuration to output file is as complete as possible
1. Initialization parameters: read and merge parameters from configuration files and Shell statements to obtain the final parameters; 2. Start compiling: initialize parameters, load the configuration plug-in, and perform method compiling. 3. Compile module: from the entry file, call all configured Loader, and recursive module 5 for dependencies. 6. Output resources: assemble chunks containing multiple modules one by one according to the dependencies between entries and modules, and convert each Chunk into a separate file and add it to the output list. This step is the last chance to modify the output content. 7. Output complete: After determining the output content, determine the output path and file name based on the configuration, and write the output content to the file system.Copy the code
5. What is the hot update for Webpack?
Hot Update is also called Hot Module Replacement (HMR for short). Based on devServer, the production environment does not need devServer, so the HMR function cannot be used in the production environment: Style files: you can use THE HMR function, because style-loader implements JS files: by default, HMR function is not available, you need to modify JS code to add support for HMR function. Entry files do not have HMR function, only can handle non-entry JS files HTML files: default does not have HMR function, and will result in HTML files cannot be hot updated (i.e. no response to modification) ['./ SRC /js/index.js','./ SRC /index.html']Copy the code
6. How to optimize front-end performance with Webpack?
Optimizing front-end performance with WebPack means optimizing the output of WebPack so that the packaged end result runs quickly and efficiently in the browser. Compress the code. Remove unnecessary code, comments, simplify code writing, and so on. Webpack UglifyJsPlugin and ParallelUglifyPlugin can be used to compress JS files, using CSSNano (CSS-loader? Minimize) to compress CSS using CDN acceleration. During the build process, the referenced static resource path is changed to the corresponding path on the CDN. You can use Webpack for the output parameter and publicPath parameter of each loader to modify the resource path and remove dead code. Remove pieces of code that never go anywhere. Common code can be extracted by appending the parameter optimize-minimize at webpack startup. In the development environment: enable the HMR function, optimize the packaging build speed configure devtool: 'source-map' to optimize code run for performance in production environments: 1. OneOf optimization by default, if there are 7 or 8 loaders, each file must be processed by these 7 or 8 loaders, which wastes performance. If you use oneOf, you can directly use it to improve performance 2. Enable Babel cache. When a JS file changes, other JS resources do not change. Lazy loading and preloading 5.WA website offline access 6. Multi-process packaging Enable multi-process packaging, mainly processing JS files (babel-Loader takes a long time to work), process startup approximately 600ms, only when the work consumes a long time, need multi-process packaging. DLL packages all third-party libraries into a bundle, which is too large, resulting in slow packaging speed. DLL packages third-party libraries into multiple bundles to optimize the speedCopy the code
7. How to speed up webpack construction?
In the case of multiple entrances, Extract common code using CommonsChunkPlugin extract common libraries using externals configuration precompile resource modules using DllPlugin and DllReferencePlugin NPM packages that we reference but never modify are precompiled using the DllPlugin, and precompiled modules are loaded using the DllReferencePlugin. Webpack-uglify-parallel is used to improve the compression speed of uglifyPlugin. In principle, Webpack-Ugli-fi - Parallel adopts multi-core parallel compression to improve the compression speed, and uses tree-shaking and Scope compensation to remove redundant codeCopy the code
8. What are the common plugins? What problems do they solve? * * *
Html-webpack-plugin: Can copy a structured HTML file and automatically import all the resources packaged output (JS/CSS) Optimize - CSS -assets-webpack-plugin: optimize- CSS -assets-webpack-plugin: optimize- CSS -assets-webpack-plugin: Compress CSS uglifyjs-webpack-plugin: compress JS commons-chunk-plugin: extract common codeCopy the code
9. What is tree-shaking? Remove excess code
Tree-shaking can be used to weed out dead code in javascript. It relies on static ES6 modular syntax, such as importing and exporting. Tree-shaking was first seen in rollup, and was introduced in WebPack 2.0. Using tree-shaking in CSS requires importing Purify-CSSCopy the code
Modularity CommonJS and ES6 modularity?
ModuleA = require('./moduleA'); CommonJS: require('./moduleA'); module.exports = moduleA.someFunc; Export default import {readFile} from 'fs'; import React from 'react'; Export function hello() {}; export default { // ... };Copy the code
11. What does the build tool do:
1. Code conversion: TypeScript to JavaScript, SCSS to CSS, etc. 2. File optimization: compress JavaScript, CSS, HTML code, compress and merge pictures, etc. 3. Code segmentation: extract the common code of multiple pages, extract the code that does not need to be executed on the first screen and load it asynchronously 4. Module merge: In a modularized project, there will be many modules and files, and you need to build functionality to merge modules into a single file. 5. Automatic refresh: monitor local source code changes, automatically rebuild, refresh browser 6. Code validation: Verifies compliance with specifications and unit tests before submitting code to the repository. 7. Automatic release: after updating the code, automatically build the online release code and transfer it to the release system.Copy the code