webpack 4 Common
initialization
npm init
// Webpack 4.0以后需要单独安装
npm install webpack webpack-cli --save-dev
Based config
entry: './src/index.js', mode: 'development', output: { filename: 'main.js', path: path.resolve(__dirname, 'dist') }
Field Description
- entry: entry file. Is typically a string, or a plurality of arrays may be used json
entry:"a.js"; entry:["a.js","b.js"]; entry:{ index:["a.js"], index2:["b.js"] }
- output: json file export
output : { fileName:"a.js", path:path.resolve(__dirname,"dist"); }
- mode mode provides configuration options
mode : production;
mode : development;
- loader module for converting the source code
module:{ rules:[ { test:/\.css$/, use:[ { loader:"style-loader" }, { loader: 'css-loader', options: { modules: true } } ] } ] }
- plugin plugin aims to solve other things loader can not be achieved.
plugin : [ new webpack.optimize.UglifyJsPlugin(), new HtmlWebpackPlugin({template: './src/index.html'}) ]
webpack common
module.noParse
Prevent webpack parse those files match the criteria, ignoring the folder should not contain calls import, require, define or any other import mechanisms, ignore the library can improve build efficiency.
Open sourceMap
css option provided in the cssloader {sourceMap: true}, js in devtool: 'inline-source-map'
module.exports = { entry:"./index.js", output:{ filename:"[name].js" }, module:{ rules:[ { test:/\.(sc|c|sa)ss$/, use:[ { loader:"css-loader", options:{ sourceMap: true } } ] } ] }, devtool:"source-map" }
devtool optional value
1. source-map
2. inline-source-map
3. inline-cheap-source-map
4. inline-cheap-module-source-map
5. eval
Hot update (webpack.HotModuleReplacementPlugin)
const webpack = require('webpack'); module.exports = { devServer: { ContentBase: path.join (__ dirname, 'dist'), // directory page loaded local server where clinetLogLevel: 'warning', // possible values are none, error, warning or info (default value) Hot: to true , // start hot update replacement properties, need to meet webpack.HotModuleReplacementPlugin plug- Host: '0.0.0.0', // start the server Host port: 7000, // port number of the compress: to true , // for all services enable gzip compression overlay: to true , // show in the browser full-screen coverage stats: "errors-only", // show only package error Open: to true, // When you enable the "Open", dev server will open the browser. Proxy: { // Set Agent "/ API" : { target: "http://localhost:3000", pathRewrite: {"^/api" : ""} } } }, plugins::[ new webpack.NamedModulesPlugin(), new webpack.HotModuleReplacementPlugin() ] } // package.json { ..... script:{ "dev":"webpack-dev-server --config webpack.dev.js" } ..... }
Alternatively alias (resolve.alias)
The key to the end of the given object to add $ to indicate precisely match
module.exports = { resolve:{ alias:{ '@src':path.resolve(__dirname, 'src/') } } }
resolve configurable parameters:
aliasFields
If the license is not incorporated enforceExtension no extension file is true, for example, you may use false require ( "./ index") true must require ( "./ index.js");
extensions automatically parsed to determine the extension default value is [ ".js", ". json"], while import statement did not bring the file suffix, Webpack will automatically bring the suffix whether to try to access the file exists.
css individually packaged (mini-css-extract-plugin)
const MiniCssExtractPlugin = require('mini-css-extract-plugin'); module: { rules: [ { test: /\.(sc|c|sa)ss$/, use: [ MiniCssExtractPlugin.loader, { loader:"css-loader", options:{ sourceMap: true } }, ] } ] }, plugins: [ new MiniCssExtractPlugin({ filename: '[name] .css', // file name final output chunkFilename: '[id] .css' }) ]
Js compression and css (uglifyjs-webpack-plugin, optimize-css-assets-webpack-plugin)
the require UglifyJsPlugin = const ( 'UglifyJS-WebPACK-plugin'); // JS compression const = OptimizeCssAssetsPlugin the require ( 'Optimize-CSS-Assets-WebPACK-plugin'); // compression CSS module.exports = { // ... omitted plugins: [ // ... omitted new new OptimizeCssAssetsPlugin ({}), new new UglifyJsPlugin ({ // if there is no change no compression JS Cache: to true , // whether to enable parallel compression; parallel: to true , sourceMap: true }) ], }
Introduction of dynamic document processing html (hash) (HtmlWebpackPlugin)
const HtmlWebpackPlugin = require('html-webpack-plugin'); plugins: [ new HtmlWebpackPlugin({ title: "title!", // generate the file header filename: "main.html", // final generated file name Minify: { // compression option collapseWhitespace: to true , // remove spaces removeComments: to true , // remove the comment removeAttributeQuotes: to true , // remove the double quotes } }) ],
Cleanup directory (clean-webpack-plugin)
const {CleanWebpackPlugin} = require('clean-webpack-plugin'); plugins: [ new CleanWebpackPlugin() ],
Image processing and optimization (file-loader (processing), image-webpack-loader (optimization))
module: { { test: /\.(png|svg|jpg|jpeg|gif)$/, include: [path.resolve(__dirname, 'src/')], use: ["file-loader",{ loader: "image-webpack-loader", options: { mozjpeg: { progressive: true, quality: 65 }, optipng: { enabled: false }, pngquant: { quality: '65-90', speed: 4 }, gifsicle: { interlaced: false }, webp: { quality: 75 } } }, ] }] },
Picture base64 processing (url-loader can not be used with image-webpack-loader)
module: { { test: /\.(png|svg|jpg|jpeg|gif)$/, include: [path.resolve(__dirname, 'src/')], use: [ { Loader: 'URL-Loader', // depending on the picture size, the picture is converted into Base64 Options: limit {: 10000 }, }, ] }] },
Font Handling (file loader)
module: { { test: /\.(woff|woff2|eot|ttf|otf)$/, include: [path.resolve(__dirname, 'src/')], use: [ 'file-loader' ] } },
The combined extracts common configuration and the configuration (webpack-merge)
const merge = require('webpack-merge'); const common = require('./webpack.common.js'); let devConfig = { // configs... } module.exports = merge(common, devConfig)
Proxy settings
devserver: { // ... omitted other Proxy: { "/ API": { // request '/ api' beginning, jump to the following target configuration target: "http://192.168.30.33:8080 " , Pthriawrite: { "^api": "/mock/api" } } }
Configure external expansion (externals)
When we use the CDN introduced jquery, we do not want it packaged into the project, we can expand the configuration options for external externals, these do not need to be excluded from the bundle packaged module's output: <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
Configuration externals:module.exports = { // ... 省略其他 externals: { jquery: 'jQuery' }, }
Packaging optimization analysis report and summary (webpack-bundle-analyzer)
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; module.exports = { plugins: [ new BundleAnalyzerPlugin() ] }
Code division (SplitChunksPlugin) (for multiplexed volume greater than 30K)
{ optimization.splitchunks parameters: { Most small file size after the separation minSize bytes MinChunks before separation, (i.e. the number of a file js introduced by the require or import) of the block number is introduced MaxInitialRequests a maximum number of files can be loaded in parallel file entry maxAsyncRequests inner file (second layer) when the maximum number of parallel load demand loading name code block for controlling named after separation, when the cache group (we will discuss later) there is a match, using the name of the group name value buffer, if there was [Source] ~ [Key value entry]. js format automaticNameDelimiter modify the above, " ~", if read: "-" is separated js default naming rule is [source] - [entry key value] .js test for a predetermined set of matching cached file location, test: / the node_modules / is the matching module corresponding folder CacheGroups target name is set cache is actually stored code block separation rule, the reason will be called the cacheGroup webpack rule is placed in the cache stream file corresponding matching blocks corresponding to the stream, thereby generating the separated blocks. Type of block chunks matching: initial (original block), async (asynchronous demand loading block), all (all blocks) } } optimization: { runtimeChunk: { "name": "manifest" }, splitChunks: { chunks: 'all', Cache groups: { common: { minChunks: 2 , name: 'commons', chunks: 'async', priority: 10, reuseExistingChunk: true, enforce: true } } } }
A package can be import of js
output: { Library: "myDemo", // If you use the script tag introduced in HTML pages packed result file, myDemo corresponding value of the variable will be the entry file (entry file) return value. libraryTarget: "commonjs2" }
libraryTarget:
-
"Var" - direct the output variables (default mode library) var Library = xxx (default)
-
"This" - this this by setting the attribute of the output [ "Library"] = xxx
-
"Commonjs" - Output exports [ "Library"] by setting the properties of the exports = xxx
-
"Commonjs2" - module.exports property by setting the output module.exports = xxx
-
"Amd" - amd way to output
-
"Umd" - combined commonjs2 / amd / root
Global introduced package (ProvidePlugin)
plugins: [ // provide global variables used in the module without using require, import introducing new new webpack.ProvidePlugin ({ $: "jquery", jQuery: 'jquery' }), ]
Global constants (DefinePlugin)
plugins: [ new webpack.DefinePlugin({ 'url':'www.baidu.com' }), ]
copy the file (copy-webpack-plugin)
npm install --save-dev copy-webpack-plugin const CopyWebpackPlugin = require('copy-webpack-plugin'); new CopyWebpackPlugin([ { from:__dirname+'/public/lib', to:__dirname+'/build/lib' } ])
Optimization module search path resolve.modules
Webpack of resolve.modules configuration module library (ie node position modules) is located, appears in the js in import 'vue' This is not a relative, not an absolute path is written, the node will go to find the next modules directory. But the default configuration, will use a recursive search of ways to look up, but usually only one project directory node modules, and is in the root directory of the project, in order to reduce search, you can specify the node directly to the full path of the modules
const path = require('path'); function Resolve (the dir) { // converted to absolute path return path.join (__ dirname, the dir); } resolve: { modules: [ // optimization module search path path.resolve ( 'the src' ), path.resolve ( 'node_modules') // specify the location where node_modules When you import third-party modules directly from this path search to find ] }
Configured src? After directory location, due util in the src directory which can be introduced in util utility functions with the following way// main.js import dep1 from 'util/dep1'; import add from 'util/add';
Multithreading package (not recommended for small projects, but will slow)
const HappyPack = require('happypack'); OS const = the require ( 'OS'); // system operating module provided by node // ? My system according to the number of kernel threads specified number of pools can also be other number? Const happyThreadPool = HappyPack.ThreadPool ({size:. Os.cpus ()} lenght) module: { rules: [ { test: /\.js$/, use: 'happypack/loader?id=babel', exclude: /node_modules/, include: path.resolve(__dirname, 'src') } ] }, plugins: [ new new HappyPack ({ // basic parameter setting ID: 'Babel', // above the rear loader specified ID? loaders to: [ '? cacheDirectory Babel-loader'], // loader actual matching process threadPool: happyThreadPool, verbose: true }), new new Happypack ({Configuration} Other loader) ]