preface
I have studied Webpack systematically before, but I have not had time to properly integrate and summarize it. Here, I have recorded the notes and related knowledge points of learning Webpack before, and the relevant codes have been uploaded to Github
Here’s a mind map built by WebPack:
Webpack structure
First we need to understand a file structure that WebPack builds
- entry
- output
- loaders
- plugins
- mode
entry
Entrance to the file
Modules. Exports = {// specify an entry: './ SRC /main.js', // single entry // multiple entry // entry: {// app: './src/app.js', // adminApp: './src/adminApp.js' // } }Copy the code
output
The packaged file holds the article
Module. export = {output: {filename: '[name].js', // name equivalent to wildcard path: path.join(__dirname,'dist')}}Copy the code
loaders
Mainly used for files that WebPack cannot parse
Module. export = {module: {/* * [modified] : loaders = {module: {/* * [modified] : loaders = {module: {/* * // NPM install --save-dev css-loader style-loader {test: /. CSS $/, // loader: 'style-loader! Css-loader 'use: ['style-loader', 'css-loader'] {/* * [change] : {test: /.string$/, use: { loader: 'html-loader', options: { minimize: true, removeAttributeQuotes: False}}}, / * * [changes] : image file load change and handled separately and font file * / / / picture configuration {test: /. (PNG | JPG | GIF) $/, use: [{loader: 'url-loader', options: {/* * 【 modify 】 : base64 for images < 2KB */ limit: 2048, name: 'the resource / [name] [ext]'}}}], / * * [changes] : font file load changes * / / / fonts icon configuration {test: /. (eot | SVG | the vera.ttf | woff | woff2 | otf) $/, use: [{ loader: 'url-loader', options: { limit: 8192, name: 'resource/[name].[ext]'}}]}, // Introduce the use of. Vue files // NPM install --save-dev vue-loader vue-template-compiler {test: /.vue$/, loader: 'vue-loader' } ] }, }Copy the code
plugins
Mainly used for packaging optimization, resource management and injection of environment variables
Common plugins are as follows:
The name of the | describe |
---|---|
CommonChunksPlugin | Will chunks the same module codeExtract to a public JS |
CleanWebpackPlugin | Cleaning up the build directory |
ExtractTextWebpackPlugin | Extract CSS from the package file into a separate CSS file |
CopyWebpackPlugin | Copy files or folders to the build’s output directory |
HtmlWebpackPlugin | Create HTML to host the output package file |
UglifyjsWebpackPlugin | Compression js |
ZipWebpackPlugin | Generate a ZIP package from the packaged resources |
Common loaders and plugins
Scop reactorarily resolves a large number of closures for packaged code
Effect: Reduces function declaration code and memory overhead
Add the following configuration to your plugins
/ / open Scop Hosting, the default open new production environment webpack. Optimize. ModuleConcatenationPlugin (),Copy the code
SplitChunksPlugin performs common script separation
Chunks that
- Async Libraries introduced asynchronously are detached (default)
- Initial synchronizes the imported libraries for separation
- All All imported libraries are separated (recommended)
The detailed configuration is as follows:
module.exports = { optimization: { splitChunks: { chunks: 'async', minSize: // The minimum size of a new code block will be broken up. Only the bundle >= minSize will be broken up. MaxSize: 0. MaxAsyncRequests: 3 maxAsyncRequests: 3 maxInitialRequests: 3, // The maximum number of parallel requests to an entry automaticNameDelimiter: '~', // The linker of the filename name: true, cacheGroups: {vendors: {test: /[\/]node_modules[\/]/, priority: -10 }, default: { minChunks: 2, priority: -20, reuseExistingChunk: true } } } } };Copy the code
Html-webpack-externals-plugin optimizes packaging speed
Base library separation
Install HTML – webpack – externals – the plugin
npm i html-webpack-externals-plugin -D
Copy the code
The configuration in plugins is as follows
new HtmlWebpackExternalsPlugin({ externals: [ { module: 'react', entry: 'https://11.url.cn/now/lib/16.2.0/react.min.js' global:' React '}, {module: 'the React - dom, entry: 'https://11.url.cn/now/lib/16.2.0/react-dom.min.js' global:' ReactDOM '}}),Copy the code
Index.html joins the link
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, Initial scale=1.0"> <title>Hello Webpack</title> </head> <body> <div id="root"></div> <! - the react, react - dom to extract the configuration - > < script type = "text/javascript" SRC = "https://11.url.cn/now/lib/16.2.0/react.min.js" > < / script > < script type = "text/javascript" SRC = "https://11.url.cn/now/lib/16.2.0/react-dom.min.js" > < / script > < / body > < / HTML >Copy the code
Clean-webpack-plugin (Clean up the dist directory at build time)
Installing a plug-in
npm i clean-webpack-plugin -D
Copy the code
Configuration is as follows
var { CleanWebpackPlugin} = require('clean-webpack-plugin'); Module.export = {plugins: [new CleanWebpackPlugin(), // Clean up dist directory]}Copy the code
Px2rem-loader implements mobile adaptation
The installation
npm i px2rem-loader -D
Copy the code
npm i lib-flexible -S
Copy the code
Rule configuration
{ test: /.less$/, use: [ 'style-loader', // MiniCssExtractPlugin.loader, 'css-loader', 'less-loader', { loader:'px2rem-loader', options : RemUnit: 75, // 1 rem = 75pxCopy the code
Lib-flexible was introduced in index. HTML
Postcss +autoprefixer implements cSS3 automatic prefix completion
Install postCSS-Loader and autoprefixer
npm i postcss-loader autoprefixer -D
Copy the code
Rule configuration
{
test: /.less$/,
use: [
'style-loader',
// MiniCssExtractPlugin.loader,
'css-loader',
'less-loader',
{
loader : 'postcss-loader',
options : {
plugins: ()=> {
require('autoprefixer')({
browsers: ['last 2 version','>1%','ios 7']
})
}
}
}
]
},
Copy the code
Implement multi-page packaging
Install glob to implement the directory page traversal function
npm i glob -D
Copy the code
Configuration is as follows
Const glob = require('glob') var getHtmlConfig = function (name, const glob = require('glob'); Title) {return {template: 'index.html', // specify the output template filename: 'view/' + name + '.html', // output filename CLS title: Title, / / can be set to the template variable names, HTML template invokes the htmlWebpackPlugin. Options. The title can be used to inject: true, hash: true, chunks: ['common', name] // What code blocks to introduce in the output HTML file}; }; HtmlWebpackPlugin setMap = () => {const entry = {}; const htmlwebpackPlugin = [] const entryFiles = glob.sync(path.join(__dirname,'.. /src/views/common/*/index.js')); Object.keys(entryFiles).map((index)=>{ const entryFile = entryFiles[index]; const match = entryFile.match(/common/(.*)/index.js/); const pageName = match && match[1]; htmlwebpackPlugin.push(new HtmlWebpackPlugin(getHtmlConfig(pageName,pageName))); entry[pageName] = entryFile; }) return { entry, htmlwebpackPlugin } } const {entry,htmlwebpackPlugin} = setMap(); Module. exports = {entry: entry, output: {filename: '[name]_[chunkhash:8].js', // name equivalent to path: path.join(__dirname, 'dist') }, plugins: [ ].concat(htmlwebpackPlugin), }Copy the code
Webpack implements SSR (server-side) packaging
What is Server-side rendering (SSR)?
Render: HTML + CSS + JS + Data -> Render HTML
Server:
- All resources such as templates are stored on the server
- Intranet machines pull data faster
- One HTML returns all the data
Server side render & client side render
Summary: The core of server-side rendering (SSR) is to reduce requests
Reference: www.freesion.com/article/419…