Basic use of webpack (includes plugins plugin)

One: Concept

Essentially, webpack is a static module bundler for modern JavaScript applications.
When webpack processes an application, it recursively builds a dependency graph that contains every module the application needs, and then converts all
All files are processed by webpack to generate html,css, pictures, js modules and package them into one or more bundle s. As shown below:

Two: installation

1. Create a package with files

1. Global installation

npm install -g webpack webpack-cli

2. Check the version number after installation

webpack -v

3. Initialization project

1. Enter the webpack directory and execute the project file environment

npm init -y

2. Create the src folder
3. Create herder.js under src

 var header = document.createElement("div");
 header.innerHTML = "Hello webpack5.0";
 export default header;

4. Create index.js under src

import header from './header'
import './assets/base.css'
// import image
import pic from './assets/pic4.png';

// Create a picture
var img  = document.createElement("img");
// Specify image size and src
img.src = pic;
// Insert into body

import pic2 from './assets/sun.jpeg';
var img2 = document.createElement("img");
img2.src = pic2;

Fourth, JS packaging

1. Create a configuration file webpack.config.js in the webpack directory
The following configuration means: read the content of main.js (entry file) in the src folder of the current project directory, analyze resource dependencies, package the relevant js files, and put the packaged files in the dist folder of the current directory. , the packaged js file is named bundle.js

const path = require("path"); //Node.js built-in modules
module.exports = {
    entry:'./src/index.js',//Entry (from which file webpack starts running)
        path:__dirname+'/dist', //directory, __dirname the current absolute directory
        filename:'main.js',//Packaged js file name

2. Configure the npm run command of the project and modify the package.json file

"scripts": {
    "build": "webpack",

Run npm command to execute packaging

npm run build

3. Create a folder dist in the webpack directory, and create index.html under dist
reference bundle.js

     <script defer="defer" src="dist/bundle.js"></script>

4. View index.html in the browser

5. CSS Packaging

**1, loader loader

Install style-loader and css-loader

Webpack itself can only deal with JavaScript modules, if you want to deal with other types of files, you need to use the loader for conversion.

Loader can be understood as a converter of modules and resources.

First of all, we need to install the relevant Loader plugins, css-loader is to load css into javascript; style-loader is to let javascript know css and insert css into style tag

npm i style-loader css-loader -D

2. Modify webpack.config.js

const path = require("path"); //Node.js built-in modules
module.exports = {
    module: {
        rules: [  
                test: /\.css$/,    //Packaging rules are applied to files ending in .css
                use: ['style-loader', 'css-loader'] //Use two loader s

3. Create assets in the src folder and create style.css under assets

    background-color: #f70;

4. Modify .js under src
Introduce style.css on the first line

import './assets/base.css'

5. View index.html in the browser
See if the background changes color?

6. Load the file
Since files like .png are not a JavaScript module, you need to configure webpack to use file-loader or url-loader to handle them appropriately.

The benefits of converting resource URL s are:

file-loader can specify where to copy and place resource files, and how to use version hash naming for better caching. Additionally, this means that you can manage image files nearby, and you can use relative paths without worrying about deploying URL s. With the correct configuration, webpack will automatically rewrite the file paths to the correct URL s in the bundled output.

url-loader is based on file-loader. If the file is relatively small, it is converted to base64 format to reduce the number of http requests. If the file is larger than the threshold, it will be automatically handed over to the file-loader for processing.

Install: npm i file-loader url-loader -D

Modify webpack.config.js

const path = require('path')

module.exports = {
    entry:'./src/index.js',//Entry (from which file webpack starts running)
        path:__dirname+'/dist', //Table of contents
        filename:'main.js',//Packaged js file name
    mode:"production",//Mode Product mode, production, development mode development
        // rule
            // When encountering files ending with .css, use style-loader and css-loader
                        // Pack base64 if less than 10k
                        limit:10240,//If the file is less than 3k convert to base64 code format 


Six: devServer local server

1. Role: start a server locally
2. Installation

npm i webpack-dev-server

3. Configuration

  • Modify in webpack.config.js
//Modify in webpack.config.js
   host:"localhost",   //local domain name
   port:"8080",   //The port number
   hot:true,  //Hot update
   open:true,//Open browser automatically
   proxy:{},//Proxy, the same as the proxy configuration in vue.config.js
  • Modify in package.json
    "serve":"webpack serve"

4. Run

npm  run serve

Seven: plugins plugin

1. Function: package, compress, and clean up during the webpack running process

2. Use

  • 2.1 html-webpack-plugin Copy the packaged js of the template html plugin to the dist directory
//01 Installation
npm i html-webpack-plugin
//02 Import
const HtmlWebpackPlugin = require("html-webpack-plugin")
//03 Use, modify in webpack.config.js
   // Instantiate the plugin (insert public index.html into main.js (packaged file) and copy it to the dist directory)
   new HtmlWebpackPlugin({template:"./public/index.html"})
  • 2.2 CleanWebpackPlugin cleans the /dist folder

install npm i clean-webpack-plugin -D

const { CleanWebpackPlugin } = require('clean-webpack-plugin')
plugins: [
  new CleanWebpackPlugin({
		cleanAfterEveryBuildPatterns: ['dist'],
  • 2.3 Optimize optimizes the css plugin

Install optimize-css-assets-webpack-plugin -D

const optimizecss = require('optimize-css-assets-webpack-plugin')
plugins: [
  optimization:{//Optimization options
     minimizer:[new optimizecss()],
  //2. Use plugins
  new miniCssextractPlugin({

  • 2.4 ExtractTextPlugin extracts css styles
    The main purpose of this plug-in is to extract the css style and prevent the page style loading disorder caused by packaging the style in js.

install npm i mini-css-extract-plugin -D

const miniCssextractPlugin = require('mini-css-extract-plugin')
plugins: [
  //1. Use loader
  //2. Use plugins
  new miniCssextractPlugin({

Tags: Front-end Javascript Webpack

Posted by nobertos on Wed, 07 Sep 2022 01:39:37 +0930