preface

After sharing the basic configuration of webpack last time, this time will share some common configuration plug-ins in the work of the project, will also include some of their own understanding of the plug-in feel good, if the analysis is not in place, welcome to correct, well, these things have documents, big guys can bypass.

Many plugins have been deprecated since Wepack4, and only those supported by Webpack4 (including plugins before 4) will be explained.

After the last share, some netizens left a message questioning: cheat xiaobai praise, whether original, whether copy others and so on, of course, there are a lot of netizens support and encouragement, regardless of praise or criticism, Su Nan are very grateful, is you let me realize their own shortcomings and advantages and disadvantages.

Everybody’s message, reminds me of his sad, just starting front the early basic self-study by themselves, and no one to take, encounter problems like a headless fly, everywhere disorderly bump a search on the net, baidu never deceives me, in the ordered one advertisement, after over ten after eight pages finally found the solution of the problem.

As a beginner of front-end, I once lamented that I could write something in the editor and run it on the web page. I even lamented that when JS wrote “Alert Hello world”, the browser would automatically pop up a window, as if the whole world was waving to you. The excitement at that time was indescribable, even imagining that one day there might be tens of millions of users using your writing. Although not to billions, but still have to dream

These days I have been wondering whether the summary of this plug-in should be continued. From writing blog to today, nearly two months, is also a new person, although the technical aspects of the work for several years, but also dare not say much cattle B, the original intention of writing blog is to their own work encountered problems/experience to make a summary, as the saying goes: a good memory is better than a bad pen; At the same time, I also hope to share my problems with others, so that gay friends who meet the same problems can avoid a little detours.

Finally, after thinking about it for a long time, I realized that no one is perfect, no matter what you do, there will always be a different voice, and no matter what you share, there will always be someone who needs or despises. So go your own way, let others take a taxi, adhere to what you want to try to become what you want to become, is the biggest affirmation of their own ———— to once entered the front of our.

  • To do what you want to do and love who you deserve;
  • To be what you like,
  • Go shine! Full of strength,
  • Full days are the best!

Good morning, everyone. This is @IT· Teamhead Alliance. I am Su Nan, chief Pit filling Officer, sharing with you growing up to be a warm siege lion. Public account: honeyBadger8, group: 912594095

mini-css-extract-plugin

  • CSS – extract, see the name to understand the extraction of CSS.
  • We might have used it before thatextract-text-webpack-pluginIt’s a little bit more. What’s the advantage?
  • The extract-text-webpack-plugin extracts CSS based on which instance you create or configure multiple portal chunks.
  • For example, if you configure an entry file, eventually all the CSS will be extracted in one style file,
  • If you create more than oneextract-text-webpack-pluginInstance, generate multiple CSS files,
  • whilemini-css-extract-pluginBy default, it modularizes your styleoutputAsynchronous loading on demand is no longer just the prerogative of JS;
  • Example:
The compilation results are compared

//extract-text-webpack-plugin
config.module.rules.push({
  test: /\.(scss|css)$/.use: ExtractTextPlugin.extract({
	use: [
	  "css-loader",
	  { // Column exchange by Chief Pit Filling Officer Su Nan: 912594095, public account: honeyBadger8
		loader: 'postcss-loader'.options: {
		  plugins: [
			require('autoprefixer') ({// Add the prefix
			  browsers: CSS_BROWSERS,
			}),
		  ],
		  minimize: true}},"sass-loader"
	]
  })
})
config.plugins.push(new ExtractTextPlugin({
  filename: 'css/[name].css'.disable: false.allChunks: true,}));//mini-css-extract-plugin compiles package
config.module.rules.push({
  test: /\.(scss|css)$/.// Handle CSS/SCSS simultaneously
	use: [
	  {
		loader: MiniCssExtractPlugin.loader,
	  },
	  "css-loader"./ / CSS processor
	  {
		loader: 'postcss-loader'./* Postcss is a plugin that integrates with existing tools. It is rarely used alone. It is used with autoprefixer to add prefixes for different browsers to achieve better compatibility. Color :var(--theme-color,#42b983); * /
		options: {
		  plugins: [
			require('autoprefixer') ({browsers: CSS_BROWSERS,
			}),
		  ],
		},
	  },
	  "sass-loader" // A sASS processor, or even a less processor
	]
})

config.plugins.push(new MiniCssExtractPlugin({
  filename: 'css/[name].css'.// Output is the same as output
  chunkFilename: 'css/[id][chunkhash:8].css',})); config.plugins.push(new OptimizeCssAssetsPlugin({})); // Compress the file

Copy the code

optimize-css-assets-webpack-plugin

  • It is used in the above example to compress CSS files,
  • assetNameRegExpBy default, all CSS files will be compressed. This field can specify certain files to be processed.
  • cssProcessor: Specifies a csS-optimized processor, defaultcssnano.
  • cssProcessorPluginOptions: cssProcessor behind can follow a process method, returns a promise, and cssProcessorPluginOptions is one the options parameter options!
  • canPrint: Boolean, whether to display compiled messages on the console, not found any use!
  • Pothole: it is recommended to use the higher version of the package, the lower version of the previous encounter style loss to each browser prefix dry problem,
new OptimizeCssAssetsPlugin({
  assetNameRegExp: /\.optimize\.css$/g,
  cssProcessor: require('cssnano'),
  cssProcessorPluginOptions: {
    preset: ['default', { discardComments: { removeAll: true}}], //autoprefixer: {browsers: CSS_BROWSERS}, canPrint:true
})
Copy the code

SplitChunksPlugin, RuntimeChunkPlugin

  • They’re from the last oneoptimizationConfiguredsplitChunks,runtimeChunkBasically the same,;
  • SplitChunksPlugin and RuntimeChunkPlugin are actually before WebPack4CommonsChunkPluginTo extract some common modules;
  • chunks: The type to process, which has three values: all,async, and initial
  • minSize: Minimum size
  • maxSize: The size of the largest package, beyond which new packages are generated
  • minChunks: references the module at least N times,
  • maxAsyncRequests: Maximum number of parallel requests loaded on demand
  • maxInitialRequests: Indicates the maximum number of initial load requests
new webpack.optimize.SplitChunksPlugin({
    chunks: 'async'.minSize: 30000.maxSize: 0.minChunks: 1.maxAsyncRequests: 1.maxInitialRequests:1.name: true.// Can be specified... .// Column exchange by Chief Pit Filling Officer Su Nan: 912594095
    
}),
new webpack.optimize.RuntimeChunkPlugin({
    name: 'manifest'.name: entrypoint= > `runtimechunk~${entrypoint.name}` // Dynamic file name
})

Copy the code

HotModuleReplacementPlugin

  • Hot update replacement, to replace the edited code without refreshing the reloaded page:
  • It only updates the changed content, so it’s fast, almost as soon as it cuts to the browser window.
  • useHotModuleReplacementPluginAfter the plugin, it will expose onemodule.hotObject, which has a number of properties below:
  • accept: It takes two parameters, one is the authorization module (can be a single file path directly, or an array containing multiple file paths), and the second parameter is the callback function, which is the logical processing to be done after the update.
  • declineSort of a blacklist, which means to ignore modules and not update them,
  • statusThe current update status can be idle, Check, prepare, ready, Dispose, apply, or fail.
  • Generally only usedacceptAt most, here’s an example;
Hot update replacement shows the process


//webpack config
plugins:[
	new webpack.HotModuleReplacementPlugin()
]

// Route entry page...if (module.hot) {
    module.hot.accept([
    	'./pages/routes'
    ], (err) => {
    	const NextRoute = require('./pages/routes')
    	// Remove the mounted React component from the DOM and reinstall it
    	ReactDOM.unmountComponentAtNode(APP_DOM);
    	ReactDOM.render(
    		<Provider store={Store}>
    			<Router routes={NextRoute} history={browserHistory}/>
    		</Provider>, APP_DOM); }); }...Copy the code

html-webpack-plugin

  • This is a plugin that I’m sure you’re all familiar with,
  • Insert compiled files (CSS/JS) into entry files, you can specify only certain files to insert, you can compress HTML, etc
  • filename: Output file name;
  • template: template file, not limited to HTML suffix oh;
  • removeComments: Remove comments from HTML;
  • collapseWhitespace: Delete whitespace and newline characters, the entire file will be pressed into a line;
  • inlineSource: The CSS and JS files inserted into the HTML should be inlined, that is, not imported as link and script.
  • inject: Whether content can be injected into the output page;
  • chunks: specifies some modules to be inserted.
  • hashHash is added to the inserted file each time to process the cache, for example:;
  • Others: Favicon, Meta, title… ;

new HtmlWebPackPlugin({
  filename: path.resolve(__dirname, '.. /assets/index.html'), 
  template: path.resolve(__dirname,".. /views/temp.html"),
  minify: {// Compress HTML file  &emsp; &emsp; removeComments:true, &emsp; &emsp; collapseWhitespace:true 
	},
  inlineSource:  '.(js|css)'.inject: false.chunks: ['vendors'.'index'].// Column by Chief Pit Filling Officer Su Nan
	hash:true, the favicon, meta, title, etc can be configured, page using "% > < % = htmlWebpackPlugin. The options. The title"... })Copy the code

uglifyjs-webpack-plugin

  • Optimization.minimizer is used by default.
  • cache: Boolean/String, String is the path to cache files.
  • test: Regular expressions, strings, and arrays can be used to match only certain files, such as /.js(? . *)? $/i;
  • parallel: enable multi-threaded parallel running to improve the speed of compilation, often compile time to hear the whir of the computer run, may be it dry, ha ha ~;
  • output.comments: Delete all comments,
  • compress.warnings: The plugin does not warn when deleting unnecessary code.
  • compress.drop_console: For those of you who like to use console, it can automatically filter them out, and you don’t need to worry about printing logs online.
  • And so on there are some such as: define the degree of compression, put forward many times but no variable value configuration, want to go further students can go official;

/ / the default:
optimization:{
	minimizer:true
};

/ / custom
minimizer: [
  new UglifyJsPlugin({
    cache: true.// cache: "assets", 
    parallel: true.// You can also specify Number, the maximum Number of parallel runs
    sourceMap: true.uglifyOptions: {
      output: {
        comments: falseAnd...// Column of Su Nan, Chief Pit Filling Officer, QQ:912594095
      },
      compress: {
	      warnings: false.drop_console:trueAnd... }}}),].Copy the code

BannerPlugin

  • This is a plugin, and what it does is when we need to add some description to the file, like version number, author, date, etc.,
  • It helps that every time you compile, plug-in some comments in the header;
  • It can be a string or an options;
  • Well, I almost forgot to mention, it’s webpackBring their ownWithout having to install additional dependencies,
The BannerPlugin inserts comments into the document


// String:
new webpack.BannerPlugin('Add some information to the file, package date:'+ new Date());

/ / custom
plugins: [
  new webpack.BannerPlugin({
  	{
		  banner: '\ n@item: Project \ n@author :suSouth \ n@date :'+new Date() +'\ n@description: Project \ n@version :'+package.version+' \n'.// The content of the comment to outputTest :string/ regular/array,// Can be used to match some files before output,
		  entryOnly: boolean, // Whether to add comments only to the entry module file;... }})].Copy the code

preload-webpack-plugin

  • Before using this plug-in, we need to know about itpreload,prefetchLiterally:preload.
  • It is very easy to load resources in advance. Add rel=”preload” tags to the resources you want to load.
  • Example:
  • whilepreload-webpack-pluginWhat it does is it does all of this for us when we compile and package,
  • After compiling, you can (specify some/all) files to be dynamically inserted intoHtmlWebPackPluginIn the configuration output file,
  • as: indicates the type of resource you preload. There can be more than one: script, font, image, style, video, etc. Please check for more detailsAPI, it can also return function;
  • include: A preloaded file to be inserted, including allChunks, Initial, asyncChunks, and array. Array indicates that certain files are to be inserted
  • fileBlacklist: indicates the file blacklist. You can specify a file or use the re to match the file.

,)

Preload-webpack-plugin Resource preloading


/ / note 1: please write configuration must be after HtmlWebPackPlugin plugin, or you will quote ` HtmlWebPackPlugin. GetHooks is not a function ` errors,
// Note 2: After webpack4, use the latest version NPM install --save-dev preload-webpack-plugin@next,

new PreloadWebpackPlugin({
  rel: 'prefetch'.as: 'script'.// as(entry) {
  // if (/\.css$/.test(entry)) return 'style';
  // return 'script'; // Column of Su Nan, Chief Pit Filling Officer, QQ:912594095
  // },
  include: 'asyncChunks'.// fileBlacklist: ["index.css"]
  fileBlacklist: [/\index.css|index.js|vendors.js/, /\.whatever/]
})


Copy the code

webpack-bundle-analyzer

  • This plugin is pretty good, highly recommended to check it out, is also the last plugin shared this time
  • Its function is to help us see very clearly and intuitively, you compiled each, each file oh, the distribution of content composition, which is conducive to our fast search package is too large, whether the content is repeated, problem location optimization;
  • After compiling, it will automatically start a service, customize configuration, open a visual window, move the mouse to the corresponding module, you can display the size of the module in a file and the status of STAT, parsed, gzipped, etc.
  • analyzerHost,analyzerPort: Specifies the IP address and port to be enabled. The default value is 127.0.0.1:8888
  • reportFilename: The path to report generation. By default, output is the project output.path.
  • openAnalyzer: Whether to open the analysis window automatically,
  • There are many other attributes, the official website also has, here is just a guide to the introduction, please big guys do not spray;
The image is taken from the official sample GIF

plugins:[
	newBundleAnalyzerPlugin({... })// The default configuration is fine for our purposes
]


Copy the code

Add-on: add-on: add-on: add-on: add-on

  • Mini-css-extract-plugin Style extraction plug-in
  • Optimize – CSS -assets-webpack-plugin
  • Html-webpack-plugin generates entry files and injects dependencies
  • Uglifyjs webpack – plugin js compressed
  • Preload-webpack-plugin Resource preloading
  • Webpack-bundle-analyzer visual compilation analysis
  • Copy-webpack-plugin file copy
  • BannerPlugin adds comments at the beginning of the file
  • typings-for-css-modules-loader
  • awesome-typescript-loader

The end:

  • Complete configuration Example

The above are the plug-ins commonly used in several projects sorted out for you today. You are welcome to add them if you don’t understand them well enough. At the same time, I have prepared an integrated and complete example of WebPack configuration for you. Of course, you can move fingers to pay attention to the lower public number is even better, thank you for your support!

Share with your heart, let’s grow up together as a lion with temperature

Author: Su Nan – Chief Pit filling officer

Link: blog.csdn.net/weixin_4325…

Communication: 912594095, public account: honeyBadger8

This article is original, all copyright belongs to the author. Commercial reprint please contact @IT· Flathead brother alliance for authorization, non-commercial reprint please indicate the original link and source.