This is the ninth day of my participation in the First Challenge 2022. For details: First Challenge 2022.

preface

Webpack has been developed in five versions so far, so if you don’t know webpack, get started. Webpack is a must-learn for Web front-end developers. This article takes a look at packaging optimizations for the basics of WebPack. Words do not say, on the pickled cabbage ~~~~

Optimize the loader

In scaffolding projects, you’ll probably all be using pre-processed CSS. Pre-processing languages such as Sass, Stylus, and less. We know that to use these pre-processed CSS you must configure the corresponding loader in webPack.

When we configure too many Loaders, a large number of codes will be converted between loaders, which will lead to a very slow startup and packaging of the project. At this time, we need to optimize the Loader. In loader configuration, we can exclude files from third-party packages to reduce the scope of loader code conversion.

module.exports = {
    module: {
        rules: [
            test: /\.css$/, 
            loader: ['style-loader'.'css-loader'].include: [resolve('src')].// Only look in the SRC folder
            // The code in node_modules is compiled so it doesn't need to be processed again
            exclude: /node_modules/]}}Copy the code

The compression code

In Webpack, we can use UglifyjsWebpackPlugin to compress JS and CSS code, so as to reduce the volume of project packaging, improve packaging speed.

Note: we do not need to use this plugin in the development environment

// Install the plug-in
npm install uglifyjs-webpack-plugin --save-dev

/ / in vue. Config. Js
/** Uglifyjs-webpack-plugin */
const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); 
/** Global variables, current environment */ 
const env = process.env.NODE_ENV; 
module.exports = { 
... 
configureWebpack: config= > {
  if (env === "production") {
    config.optimization.minimizer.push(
        new UglifyJsPlugin({
          // Test the file that matches the compression
          test: /.js(? . *)? $/i.// The file to be compressed
          include: //includes/,
          // Whether to enable file caching
          cache: true.// Whether to enable parallel compression for multiple processes
          paralleL: true.// Use uglifyOptions to remove console in production
          uglifyOptions: {
            warnings: false.compress: {drop_console: true.drop_debugger: true.pure_funcs: ['console.log']}}}}}}))Copy the code

Uglifyjs-webpack-plugin also has many configuration items for uglifyjs-webpack-plugin

Pay attention to openparallelMulti-process compression is very helpful to improve the speed of project packaging

Gzip compression

In addition to compressing JS and CSS, we can also compress webPack packed files.

opengzipAfter the compressionwebpackThe generatedjsThe size of the file will be reduced by more than 30%.

To enable gzip compression we also need a plug-in called compression-webpack-plugin and we also need to ensure that both the server and client support GZIP.

// Install the plug-in
npm install compression-webpack-plugin --save-dev

/ / in vue. Config. Js
/** Introduce compression-webpack-plugin */
const CompressionWebpackPlugin = require('compression-webpack-plugin'); 
const productionGzipExtensions = /.(js|css|json|txt|html|icon|svg)(? .*)$/i
module.exports = { 
... 
configureWebpack: config= > {
  if (env === "production") {
    config.plugins.push({
      new CompressionWebpackPlugin({
       filename: '[path].gz[query]'.algorithm: 'gzip'.test: productionGzipExtensions,
       threshold: 10240.minRatio: 0.8})})}}}Copy the code

The compression-webpack-plugin also has a number of configuration items, refer to compression-webpack-plugin

Remove the public dependencies

For some large, short update packages, we do not need to download into the project to use. We can choose to import the library using CDN, but it is better to keep the library on our own server. Webpack allows us to import some resources from outside.

In the webpack configuration there is a configuration item externals:

Instead of packing imported packages into the bundle, obtain these external dependencies at runtime.

Load the extension’s dependencies from outside rather than in the project. Obviously, this will reduce project size and package size.

To remove the common dependencies we also need to install a plugin called html-webpack-plugin. The main use of this plugin is to load the imported CDN into index.html.

If your Version of WebPack is larger than 4.0, you don’t need to install it, webPack 4.0 already comes with the plugin. The version of Webpack in this project is 4.2.15 so installation is not required

Here’s how to configure it with me:

/ / in vue. Config. Js
const baseUrl = 'https://minturechan.oss-cn-shenzheng.aliyuncs.com/npm'
const cdn = {
  js: [`${baseUrl}[email protected] / dist/vue. Min. Js `.`${baseUrl}[email protected] / dist/vue - router. Min. Js `.`${baseUrl}[email protected] / dist/vuex. Min. Js `.`${baseUrl}[email protected] / dist/iview. Min. Js `.`${baseUrl}[email protected] / dist/jquery. Min. Js `].css: [`${baseUrl}[email protected] / dist/styles/iview. CSS `]}module.exports ={
chainWebpack: config= > {
//config.plugin(' HTML ') This means to get the html-webpack-plugin ~
config.plugin('html').tap(args= > {
  if (env === "production") {
    args[0].cdn = cdn
  }
  return args
})
 }
}
Copy the code

After the configuration is done in vue.config.js we also need to import it in index.html under the public folder

<! DOCTYPEhtml>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0, user - scalable = no">
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
    <meta http-equiv="Pragma" content="no-cache" />
    <meta http-equiv="Expires" content="0" />
    <link rel="icon" href="<%= BASE_URL %>zyd.ico">
    <title>test</title>
    <% for (var i in
    htmlWebpackPlugin.options.cdn&&htmlWebpackPlugin.options.cdn.css) { %>
    <link href="<%= htmlWebpackPlugin.options.cdn.css[i] %>" rel="preload" as="style" />
    <link href="<%= htmlWebpackPlugin.options.cdn.css[i] %>" rel="stylesheet" />
    <% } %>

    <% for (var i in htmlWebpackPlugin.options.cdn&&htmlWebpackPlugin.options.cdn.js){
    %> <script src="<%= htmlWebpackPlugin.options.cdn.js[i] %>"></script>The < %} % ></head>
  <body>
    <div id="app">
    <! -- built files will be auto injected -->
    </div>
  </body>
</html>
Copy the code

Add the following code to index. HTML to import external CDN resources ~~

The last

Webpack still has a lot to offer, and this article has simply illustrated some of the basic webPack optimization configurations.

If the article has the inadequacy place, also invites everybody to criticize to point out.

Thank you for watching this article hope to give a 👍 comment collection three even! Your likes are my motivation to write.