webpack packaging tool in Vue

Posted by Jeremy_North on Fri, 31 Dec 2021 00:18:59 +0100

catalogue

1 basic concepts of webpack

2webpack usage steps

Configuration of 3webpack

4webpack development server

1 basic concepts of webpack

The official website of webpack is given below

Concept | webpack Chinese document (docschina.org)

Previously written websites have a lot of files and a large volume, so we can use it to simplify our code. Its essence is a third-party module package for analysis and packaging code.

2webpack usage steps

Before we use webpack, we need to download yarn and declare a package using the yarn init command JSON file, which contains name, version and dependent packages to be used. Install the dependency package with yarn add webpack and webpack cli - D, and configure the custom command build:scripts

It should be noted that if we are not in webpack config. JS, then our webpack will put the index. Under src JS is the packaging entry file by default, that is, the JS file will be mainly packaged, and the default output is main under dist JS file, where main JS file is the result of packaging.

// webpack package entry main js
import { addFn } from './add/add'
import { getArrSum } from './tool/tool'

console.log(addFn(5, 2));
console.log(getArrSum([5, 6, 9, 10]));
export const getArrSum = arr => arr.reduce((sum, val) => sum += val, 0)
//tool.js file
export const addFn = (a, b) => a + b
//add.js

Configuration of 3webpack

Of course, we can modify the entry and exit of webpack. At this time, we need to create a new webpack config. JS file and configure it accordingly. It should be noted that it is based on node, so it needs to comply with the commonJS specification.

// Character attribute
var path = require("path");
console.log(path.join(__dirname, './dist'))
module.exports = {
    entry: './src/main.js', // webpack portal
    output: { // Export
        path: path.join(__dirname, './dist'),
        filename: 'bundle.js'
    }
};

We have defined exits and entrances, which can be changed as needed. The following figure shows the packaging process of yarn build

We know that webpack can help us package JS files by default. For example, if we introduce many plug-ins into a JS file, such as jquery and template, we can package multiple JS files, synthesize them into a file, and then import this file into the original HTML file. It is conceivable that this is a regular process.

The problem is that if there are a lot of HTML files, the problem may be that you need to manually import files, which is prone to errors. Therefore, we use the HTML webpack plugin plug-in to carry out relevant configuration, that is, let it help us automatically generate HTML files. This HTML file is a referenced file

// Character attribute
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/main.js', // webpack portal
  output: { // Export
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
  },
  plugins: [new HtmlWebpackPlugin({ // plugins plug-in configuration
    template: './public/index.html' // Tell webpack to generate dist/html files with our own html files as templates when using plug-ins
  })],
};

As we said earlier, webpack can only package JS files. What if we need it to package CSS files?

Therefore, we need to download two plug-ins. CSS loader enables webpack to process CSS type text, and style loader can insert CSS into DOM. CSS is packaged into JS files.

      { // A specific rule object
        test: /\.css$/i, // Match css end file
        use: ["style-loader", "css-loader"], // Let the webpack user use two loader s to process css files
        // From right to left, so you can't reverse the order
        // css loader: webpack parses css files - package css code into js
        // Style loader: CSS code is inserted into the DOM (style tag)
      }

Identify the files that package the less class. Need to use less and less loader, where less loader is to identify the less file, and less is to compile less into css

      {
        test: /\.less$/,
        use: ['style-loader', 'css-loader', 'less-loader']
      }

webpack processing images uses asset module technology to process font files and image files without configuring additional loader s

It should be noted that files smaller than 8KB are transferred to base64 and packaged in JS. Files larger than 8KB are automatically named and output to dist

So why is this setting different?

The pictures are translated into base64 browser. There is no need to send a request. It can be read directly and the speed is fast. The disadvantage is that the picture is too large. Turning base64 will increase the size of the picture

      { // Configuration of picture files (webpack5 version only)
        test: /\.(gif|png|jpg|jpeg)$/,
        type: 'asset' // After matching the above files, webpack will process and package them as static resources
        // If you set the asset mode
        // Image files are distinguished by 8KB size
        // If it is less than 8KB, transfer the image file to base64 and package it into js
        // If it is larger than 8KB, directly output the picture file to dist
      }

When webpack handles font icons, you need to put the fonts font in the relevant assets folder and configure it as follows

      {
        test: /\.(eot|svg|ttf|woff|woff2)$/,
        type: 'asset/resource', // All font icon files are output to dist
        generator: { // Generate file name - define rules
          filename: 'fonts/[name].[hash:6][ext]' // [ext] will be replaced by eot/.woff
        }
      }

We can query the above related configurations in related documents. Next, let's take a look at the syntax degradation of JS by webpack

babel and babel loader are required. The first one is the JS compiler, which demotes the high version JS syntax and outputs compatible low version syntax. The second one allows webpack to translate packaged JS code

      {
        test: /\.m?js$/,
        exclude: /(node_modules|bower_components)/, // Do not match the files in these folders
        use: {
          loader: 'babel-loader', // Use this loader to process js files
          options: { // Loader options
            presets: ['@babel/preset-env'] 
// Preset: @ Babel / preset env downgrade rule - downgrade our js syntax according to the rules here
          }
        }
      }

4webpack development server

The following is a requirement. Every time the code is updated, it must be repackaged. The principle of yarn build is as follows

  • Build dependency from 0
  • The disk reads the corresponding file into memory, and the webpack starts loading
  • Then use the corresponding loader for processing
  • Output the processed contents to the specified directory on the disk

The solution is to develop a server to cache some packaged content, only repackage the modified files, and finally run them in memory for the browser, that is, run the code in the content, update them automatically, and return them to the browser for display in real time.

Therefore, we need to use the webpack dev Server package. We can start a dynamic server by commanding yarn server, and can actively set the port number of the server.

Topics: Vue Webpack