Webpack publishing strategy



In the previous article, we learned about the basic construction of webapckWebpackIt can be used to build a simple packaging environment. However,WebpackIt’s not just that simple, or it won’t be the most popular modular packaging tool in the front end

So, what other functions do we need to know? Let’s learn a little bit about it

If there are any mistakes or mistakes in the article, please refer to my friends and thank them in advance

OK, I don’t need to talk much. Here’s how


Since we are going to useWebpackFor project packaging, first of all, we must have a project like this.

Got it.WebpackWe can try to build a simplevue-cliYes, according to the official websiteloaderThere are also some simple plug-ins, as well as the.babelrcIt is easy to modify the file

The pit here:

  • babel-loaderUpgrade to8.xAfter the version, you may need simple cooperation. For convenience, sodemoVersion 7. X used directly in
  • vue-loaderUpgrading to5.xMust be introduced latervue-loader/lib/pluginPlug in, otherwise error will be reported

specificDOMEPlease click here to view the configuration

Separate third party packages

The basic configuration of the project is completed. Next, we will pack it to see the effect:

Webpack publishing strategy

If there is no problem with the previous configuration, it is basically like the figure above

From the packed files, we can see that there arehtmlPage, font file, andbundle.jsFile (Webapck4After that, there will be a default subcontracting strategy, so there will be severalbundle.jsDocument)

It’s not hard to seebundle.jsThe volume of the file is still large. Now, let’s separate the third-party package introduced by the previous project

Separate third party package inWebapck4.xBefore the release, we usedCommonsChunkPluginTo separate, to enterwebpack4.xVersion, this way is removed. As for the difference between the two, you can check the details on the official website

Now we will separate the third-party package:

staywebpack4.xIn the previous era, we need to specify the third-party package to be separated, specify the exit, and add plug-ins

Now what we need to do:

  • Designated export
output: {
    path: path.resolve(__dirname, './dist'),
    //Specifies the name of the detached package
    filename: 'js/[name].js'
  • Import configuration
        Cachegroups: {// cache group, an object. Its function is that different files can be processed differently
                Name: 'Vender', // the name of the output (the proposed third-party library)
                Test: / \. JS /, // find the file to extract through the condition
                Chunks: 'initial' // only the entry file is processed

As foroptimizationFor the configuration of this object, you can click here to view the complete configuration description

So far, we are packing once to see the effect:

Webpack publishing strategy

Obviously, third-party code has been successfully separated

Image font processing

Now, we have successfully separatedjsFile. Let’s see what we packeddistCatalog. As you can see, there are many font files in the package, and the pictures can’t be seen

Because we useurl-loaderImages are processed, so by default, all images are converted tobase64The format of is saved in ourbundle.jsAmong the documents

url-loaderAndfile-loaderThe functions are basically the same, so to speakurl-loaderyesfile-loaderAn extension of theurl-loaderThe file size is set in the configuration options of, so that the image can be converted tobase64Or directly by path

So, we can add such a restriction to the URL laoder

{ test: /\.(jpg|png|gif|jpeg|bmp)$/, use: [{
    loader: 'url-loader',
    options: {
        //Limit picture size 10240 to 10KB
        limit: 10240

After this setting, all10kbThe picture ofbase64Format addition for, greater than10kbOf will be referenced as a path

Let’s see ourdistThe distribution of contents in the folder is not obvious. So next, we sort them into different folders

{ test: /\.(jpg|png|gif|jpeg|bmp)$/, use: [{
    loader: 'url-loader',
    options: {
        //Limit picture size 10240 to 10KB
        limit: 10240,
        name: 'images/img-[hash:5].[ext]'
{ test: /\.(svg|eot|ttf|woff|woff2)$/, use: [{
    loader: 'file-loader',
    options: {
        name: 'font/[hash:7].[ext]'

Add to folder in the same way, or inoptionsAdd in optionsnameProperties, whereextIndicates that it is named after the format suffix before the file

Next, we repackage:

Webpack publishing strategy

Is it beautiful

Detach style file

stayWebpack4.xBefore, we usedextract-text-webpack-pluginThis plug-in separates the style file

Sincewebpack4After that, the official recommended separation plug-in ismini-css-extract-plugin

First, we need to download the plug-in

npm install --save-dev mini-css-extract-plugin

This is the case in the configuration file of webpack

//Step 1: introduce plug-ins and use them in plugins

new MiniCssExtractPlugin({
    Filename: 'CSS / [name]. CSS', // package file name
    Ignoreorder: false // remove warning

//Step 2: change the style loader to minicssextractplugin.loader

{ test: /\.css$/, use: [ MiniCssExtractPlugin.loader, 'css-loader'] },
{ test: /\.(sass|scss)$/, use: [MiniCssExtractPlugin.loader,'css-loader', 'sass-loader'] },

In this way, we have successfully separated the style file

Load on demand

We all know, usewebpackThe module function of can realize the module loading on demand, so how can we do some configuration in the project

webpack4.xThe above version implements the default subcontracting strategy, that is, by default,webpackCan intelligently distinguish our modules and realize the function of loading on demand

The default subcontracting policy has the following rules:

  • NewchunkIs it shared or fromnode_modulesModule
  • NewchunkIs the volume greater than30kb
  • Load on demandchunkThe number of concurrent requests for is less than or equal to5individual
  • The number of concurrent requests when the page is initially loaded is less than or equal to3individual

Because of these built-in rules, that’s why we are in the process of packaging the previous project2.js3.jsSuch a document

Here we areDemoFor a file name like this, it’s obviously not that friendly. So, we can customize these file names in the simplest way:

stayrouterIn the definition file:

Webpack publishing strategy

UsewebpackChunkNameThe keyword directly defines the name, so that when we repack, we can see that the defined name has been displayed in thedistIn the folder


Now we’re donewebapckThe basic functions of packaging and publishing, but we may find a problem: we need to manually delete them before packaging each timedistFolder. Obviously, unfriendly

We can useclean-webpack-pluginTo delete it.

The plug-in is also easy to use:

  • downloadclean-webpack-pluginPlug-in unit
  • Introduce in configuration file
const {CleanWebpackPlugin} = require('clean-webpack-plugin')

There is a small pit here. The plug-in versions are different in3.0We need to introduce this plug-in in this way

  • Use directly in plug-ins
new cleanWebpackPlugin()

So before we pack it, it will be deleted firstdistFile, and then pack it, and we don’t have to operate it manually anymore


So far, this article is almost over

completeDemo, please click here to view

Of course, aboutwebpackThere are many things we need to study in depth, such asmodeMode,resolveParsing, loading custom patterns on demand, various optimizations, and so on.webpackThe configuration is very complex, but when we are familiar with the various configurations, it is very easy to build a project

I’ve always thought that imitation is also a very effective way of progress. Interested partners can have a lookvueperhapsreactMediumwebpackConfiguration, I’m sure it will inspire you

To learn more about the front-end content, interested partners can click here and welcome to followstar

Reference resources

Webpack official website

Recommended Today

ASP.NET Example of core MVC getting the parameters of the request

preface An HTTP request is a standard IO operation. The request is I, which is the input; the responsive o is the output. Any web development framework is actually doing these two things Accept the request and parse to get the parameters Render according to the parameters and output the response content So let’s learn […]