SoFunction
Updated on 2025-02-28

Detailed explanation of the introduction summary and practice of webpack (asynchronous loading on demand, separately packaged by CSS, and generate multiple entry files)

I recently used webpack in the project, so here I plan to give a small summary of the current usage methods

Why webpack

I'll do it all at once, which is definitely an important reason.

2. Then in my previous projects, I used requireJS and AMD to achieve modular development. webpak not only supports packaging, but also supports AMD and CommonJS for modular development, so I plan to try webpack to achieve modularization.

3. My needs are simple and suitable for new webpack. I only need to generate online directories, realize modularity, compress code, etc.

webpack practice

General writing

Declare variables related to paths at the beginning, and introduce dependencies, including webpack (not necessary), and required plugins
Then, entry declares the entry-related such as file name, path, etc., output declares the path and file name related to the generated file. The module is a loader declaration for different files, and plugins declares the specific use of the plugin.

Compressed code

Here we use the built-in plugin of webpack, which we wrote in the plugins section

new ({
  compress: {
    warnings: false
  }
})

Extract public class library

I didn't use this part, but it is also based on the plug-in built-in webpack. The purpose is to integrate the used third-party libraries such as jquery into one file. Otherwise, it will be merged into one file, which will make the file particularly large

First declare a third-party library in entry

entry: {
  app: (APP_PATH, ''),
  //Add the library to be packaged in vendors  vendors: ['jquery', 'moment']
},
plugins: {
   //Package the array in the entry file into  new ('vendors', ''),
}

CSS packaged separately

Sometimes I need to package css separately as a CDN, or the situation here is that the page introduces a lot of css js files, and my js loads at the end! So if it is a css introduced in js, it will cause the page to have no style at the beginning, and know to parse it to my js! So here, css is packaged separately and introduced separately on the page!

First, you need to install plug-ins

npm install extract-text-webpack-plugin –save-dev

Then declare the plugin in

// Introduce css to package plug-in separatelyvar ExtractTextPlugin = require("extract-text-webpack-plugin");
// Set the path and file name to generate css, and automatically extract the CSS introduced in the corresponding entry js file into a separate filevar packCSS = new ExtractTextPlugin('./css/[name].'); 

Introduced and used in plugins

 plugins: [
  packCSS
 ]

We need to first refer to the corresponding css file in js

 require('./css/');

Then this plugin will automatically extract the css file in js and generate a separate file

Style processing

Install css-loader style-loader

 npm install css-loader style-loader --save-dev

css-loader will traverse the css file, find all urls(...) and process them. style-loader will insert all styles into a style on your page

 module: {
   loaders: [
    { 
     test: /\.css$/,
     loaders: ['style', 'css'],
     include: APP_PATH
    }
   ]
 }

Image processing

Install url-loader

npm install url-loader --save-dev


{
  test: /\.(png|jpg)$/,
  loader: 'url?limit=8192&name=images/[hash:8].[name].[ext]'

}

limit Set a threshold. If the image is less than this value, the base64-encoded picture will be automatically enabled. Images greater than this value will be packaged into the path corresponding to name. The image name will include the 8-bit md5-encoded name. The original name of the file, and the ext corresponding extension.

The problems I encountered in the picture are similar to css, both of which I originally introduced static resources such as css img in js. but
Because my page introduces a lot of css and js files, and my js file is loaded at the end, it will cause my js reference to css img to load at the end. This will cause the page to have no style at the beginning, and the picture will fail at the beginning.

I originally wanted to package img separately, but searching has also been practiced and I did not find a reliable way to implement it, so I put the picture in other public resource directories (~~~~(>_<)~~~, so I had to make this a temporary solution)

One page, one js file

The project I'm doing is multiple pages, so I need to generate different js corresponding to each page. The way to deal with this is that each of our js is now enrty as a different entry file. This way, set the public path in output and you can get different js files.

  entry: {
    creative: './src/static/js/apps/',
    plan: './src/static/js/apps/',
  },
  output: {
    path: 'dist/',
    filename: 'js/[name].'
  }

renew

Code segmentation and asynchronous loading

The problem I encountered today is that the page I made is divided into four steps. Each step needs to perform interface requests, page rendering, event binding and other operations on the content of the next step when entering the next step.

Previous practices

After splitting the corresponding modules of each step, I introduced each module at the beginning of the entry file through commonJS

This is how it is now

  var stepOne = require('./mods/');
  var steptwo = require('./mods/');
  ...

  // When using  ();

This approach, because of the commonJS synchronous loading mechanism, will cause the entry file to be very bloated after packaging. On the first screen, those who cannot use processing code will load at the beginning, which seriously affects the loading time of the first screen.

After the code is split

I use webpack's code splitting feature to split the code of each step to achieve on-demand loading. This is mainly implemented using webpack functions. It is very convenient. You only need to put the asynchronous loaded code into the callback function inside to implement it:

  (['./mods/'], function(){
    var stepone = require('./mods/');
    ();
  }, 'stepone'); // The third parameter sets the packaging name

Setting this way, webpack will generate split files separately, and we also need to set the name and path of the split file. I have had a lot of trouble here.

webpack uses numbers to name the split files by default. If we do not set them ourselves, we will get a file similar to this. In , we can set the name of the chunking generated file through , and the path of the chunking can be set by . You must set publicPath here, otherwise the path you get may not be the path we packaged online. My specific settings are as follows:

  output: {
    path: (__dirname, 'dist'),
    filename: 'js/apps/[name].',
    publicPath: '/dist/', // Set path    chunkFilename: 'js/apps/[name].' // Set file name  }

Summarize

Webpack feels very novel to use and is easy to buy! What I have summarized today is mostly introductory content, and I will continue to use it later~

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.