Moment For Technology

Webpack Introductory Configuration Guide

Posted on Aug. 5, 2023, 9:18 a.m. by Robert Carpenter
Category: The front end Tag: webpack

Front knowledge

  • The use of the ES6

Let/const/ arrow function /... / new / class / Promise

Inherit /this/ prototype

  • CSS syntax and layout

  • MVC concepts

Model /View / Controller / EventHub

  • Tool use

VSCode or WebStorm

Terminal command line NPM/yarn/http-server/parcel/git

  • The source code

Webpack configuration source address:

-- Source: Hungry Man Valley

Officially entered the framework stage

Before entering, learn about some tools.

You can install some tools according to CRM, or you can use the ones I recommend

In this paper, with the

"DevDependencies" : {" webpack ":" ^ 5.24.2 ", "webpack - cli" : "^ 4.5.0",}Copy the code

What is the Webpack

What does this thing do?

  • Translation code (ES6 to ES5, SCSS to CSS)

  • Build the build

  • Code compression

  • The code analysis

It's better to do it than to say so much

Use CRM (Copy, Run, Modify) to learn all the new knowledge

Implementation of the WebPack configuration process

The following steps complete the configuration process with eight goals

Translate JS with Webpack, understand the use of hash, generate HTML, introduce CSS, introduce SCSS, introduce less and stylus, introduce images, realize lazy loading, click to go to the corresponding module.

CRM learn (copy, run, modify) Webpack

Each time you complete a target configuration, you can submit the code first, in case the configuration crashes

The environment is tie-in

Global installation, can also be uneasy, I have global and local installed

  • Global installation
NPM I -g webpack@ Version number webpack-cli@ Version number //@ Add version number // or NPM: NPM I -g webpack webpack-cli // or YARN: yarn global add webpack webpack-cliCopy the code

Use NPM Info Webpack to view all webpack information. Webpack 3 itself and its CLI used to be in the same package, but after release 4, the two are separate.

Incorrect version can easily lead to some unreadable version errors, I am a global and local version

Learning method, way

Learning methods:

Enter the webpack official website

Use CRM to learn

  • Use the teaching

Go to

Find ducument navigation bar GUIDES-- Getting Started

Then copy, run, and change. The corresponding areas for CRM will also be described below. Front-end update and iteration are fast. Webpack does not have a fixed configuration and sometimes needs to be configured according to requirements. Therefore, it is particularly important to learn CRM and master methods.

Goal 1 - Translate JS with Webpack

(Turn JS into JS that runs in all browsers)

All dependencies for the installation are local -dev, because the webPack stuff is not available to users

All right, let's start the configuration

  1. Create a file called webpack-demo-1, open it with vs,

  2. Type NPM init -y in vs open terminal to initialize the configuration

Or use the command line to create and enter

mkdir webpack-demo
cd webpack-demo
npm init -y
Copy the code

After initialization, you will find a package.json file in the file

  1. Then add the dependency to the local local installation of Webpack, usingyarn add webpack webpack-cli --devOr NPM install webpack webpack-cli --save-dev.

Yarn add webpack webpack-cli --dev

My version number is

"DevDependencies" : {" webpack ":" ^ 5.24.2 ", "webpack - cli" : "^ 4.5.0"}Copy the code

There will be multiple node_modules directories after installation

  1. checkSee the version./node_modules/.bin/webpack --versionBecause it isLocal installation, so to view it this way, the call to the local Webpack is also called this way

NPX webpack(NPX will automatically find where it is locally, so you don't need to write so much), but NPX is not stable (for example, if you install node in Windows, you will not be able to use NPX. So use NPX webpack.

  1. Then create the index.js file in the SRC directory and type some simple code like console.log('hi').

Run NPX webpack-- then translate JS

There's a warning. Forget it. It's gonna beTo warn

After we run it, we see that there is a dist directory with main.js. This is what console.log('hi') in index.js translates through webpack. - This is webPack's built-in js translation function, no need to install loader and plugin.

Can that make some complicated JS translation?

Import the x.js file in the current directory

import x from './x.js'
Copy the code
  1. The SRC directorycreateX. js, export XXXexport default 'xxx'

The code in index.js does not run directly in a browser

  1. And then usenpx webpackOr./node_modules/.bin/webpack(local) to translate JS, creating dist/main.js.

Here WebPack analyzes the code and makes it usable by the browser.

Is the code in there different? Now the first small goal of js translation is complete

Additional: translation processTo warn(Mode mode)

Warning is the warning in object 1 above, although warning is fine, but it looks bad, right

Copy a warning and learn from Google

Configration in the webpack official website guide. If you can't find it, CTRL + F

Create a webpack.config.js file at the same level as SRC, warning that mode is not set, and add the following code to it

const path = require('path');

module.exports = {
    mode: 'development',
    entry: './src/index.js',
    output: {
      filename: 'main.js',
      path: path.resolve(__dirname, 'dist'),
Copy the code

Mode is used to switch modes. You can set mode to select (main.js) from development(for developers) or production(for users, minimal, uncommented). You can set it differently, and then run main.js to see the difference. Switch to Development if you are in development, or production if you are publishing

This is the result of re-running NPX webpack - without warning

Goal 2 - Understand the file nameThe purpose of the hash

Hash is used to facilitate caching, which is HTTP protocol and must be automatically supported by the browser.

(CRM Science Webpack)

Target one alerts the code in the configuration

Module. exports = {mode: 'development', entry: './ SRC /index.js', // default entry file output: {// export path: Path.resolve (__dirname, 'dist'),// Default location, file destination path filename: '[name].js', // [name] can be changed. //filename: 'index.[contenthash].js', // output file. The cache is configured with hash for easy update. [name] index},}; Dist main.js; dist main.js; dist main.js; dist main.jsCopy the code

Dist main.js after translating the entries and outputs from SRC into dist index.js. [name] can be changed. You can search webpack filename hash to see the cache configuration and change the output filename to [name].[contenthash].js

Don't you get more and more files in Dist every time YOU run Webpack? Delete distrm-RF dist before running webpack; NPX webpack, but if you forget what to do, there is a feature to add to pakage.json scripts (NPX can be omitted here because webpack will be found by default).

"build" : "rm -rf dist  webpack",
Copy the code

Then, run YARN Build or NPM run build directly each time you need to package

Additional knowledge: HTTP Cache- set Cache header cache-control

What is HTTP caching, for example

The first time you visit, return index.html,index.html will introduce download some CSS, JS files. Put these incoming files in cache, for example, slow down storage for a year without changing them. (How to update?)

The second time you visit, you only need to download index.html, but it will get the CSS and JS files from memory, thus achieving super fast access. (Why is index.html not cached?)

  • What if YOU want to update a CSS? How?

Since the cache follows the filename, just change the filename. To change the filename, hash filename to the file contents: 'index.[contenthash].js', (as long as the contents of the file are different, the file name and the content of the file have a one to one relationship) published through Webpack, so that the browser knows whether the update, the previous cache is no longer available, need to request a new one), WebPack will do this automatically

  • Why isn't index.html cached?

. Home page cache browser also how to know CSS updates are not.

Goal 3 - Use WebpackGenerate HTML

Main points: automatically change the file name, automatically add script (template), automatically use the title in the configuration

How to automatically change the file name

The official document HtmlWebpackPlugin was found

Follow the tutorial, NPM install --save-dev html-webpack-plugin or yarn add html-webpack-plugin --dev, then go to Basic Usage and add webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin'); // add const path = require('path'); module.exports = { entry: 'index.js', output: { path: path.resolve(__dirname, './dist'), filename: 'index_bundle.js',}, plugins: [new HtmlWebpackPlugin()],// add};Copy the code

After yarn build, there is index.html in dist. [name] can be changed (I changed it to index).

Dist index.html automatically introduces index.xxxxx.js. If the contents of index.js change, then the index.html will automatically update the address and add [contenthash] regardless of the file name

  • Question: What if I only have script and want to add other tags?

Continue with the CRM plug-in documentation

Here's an example:

plugins: [
    new HtmlWebpackPlugin({
      title: 'woshisb',
      template: 'src/assets/index.html'
Copy the code

Automatically add scripts and introduce templates

Use the template of the SRC /assets/index.html file and write something in it. After YARN build dist, index. HTML becomes template HTML and script and JS entry files are added where appropriate.

Automatically use the title in the configuration

To use the title in the configuration, the SRC/assets/index. The title in the HTML content into a % % = htmlWebpackPlugin. The options. The title will be using the configuration in the title: 'woshisb, can see my source

Goal 4 - Use webpackThe introduction of CSS

  • Key points:
  1. You can use JS to generate style

  2. Debug preview with webpack-dev-server

  3. You can also split CSS into files

Generate style using JS

Temporary js generation

  • How do you introduce CSS?

Create x.css and write something

I directly introduced the module x. CSS - error in x.js, interpreting CSS syntax as JS.

As the CRM

Install the CSS - loader

yarn add css-loader --dev
Copy the code

Webpack.config. js

module.exports = {
  module: {
    rules: [
        test: /\.css$/i,
        use: ["style-loader", "css-loader"],
Copy the code

Test references.css, $regular expressions (30 minutes of getting started with regular expressions) $indicates that.css ends. If the file name ends in. CSS, use csS-loader and style-loader. Yarn Build fails to install the style-loader

Install style - loader

yarn add style-loader --dev
Copy the code

-c-1 to add path preview /index.html- CSS is successfully introduced (yarn build shut down the server). You can see that there is a style tag in the head, which is the content of X. CSS

If you find any file names that end in.css, then use csS-loader to process the file. Css-loader will read the contents of this file into JS. Style-loader is what csS-loader reads. Put a style tag inside the head.

Dist, HTTP-server. -c-1

So use webpack - dev - server

CRM searches the corresponding documentation to find Using webpack-dev-server

Webpack-dev-server is a native preview of webpack that can be previewed in real time

Command to install

yarn add webpack-dev-server --dev
Copy the code

Added under mode in webpack.config.js configuration

  devServer: {
    contentBase: './dist',
Copy the code

Package. json script build. -- Open Yes Indicates whether to open the browser for you. If no, delete it

"start": "webpack serve --open",
Copy the code

Then use YARN start or NPM run start. Access the given port number. The tool is that when you change code, you don't have to rebuild it, it does it for you automatically, but it doesn't generate the dist directory, it does it in memory. The output HTML reads index.js, then translates it into a runnable JS, and then reads it into memory

CSS is selected as a file

Automatically generates + suffixes

CRM webpack css extract plugin

The installation

yarn add mini-css-extract-plugin --dev
Copy the code

Webpack. Config. Js contrast to add, style - loader (on page) and MiniCssExtractPlugin loader alternative (as a file).

const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
  plugins: [
    new MiniCssExtractPlugin({
      filename: '[name].css',
      chunkFilename: '[id].css',
      ignoreOrder: false, // Enable to remove warnings about conflicting order
  module: {
    rules: [
        test: /\.css$/,
        use: [
            loader: MiniCssExtractPlugin.loader,
            options: {
              // you can specify a publicPath here
              // by default it uses publicPath in webpackOptions.output
              publicPath: '../',
Copy the code

Yarn Build can then see a main. CSS file in dist, and a reference to main. CSS can be seen in index.html.

However, main.css references do not have file names as long as those used to import js, so main.js is cached for a year. How to update it?

Modify it on top

new MiniCssExtractPlugin({
      filename: '[name].[contenthash].css',
      chunkFilename: '[id].[contenthash].css',
Copy the code

Yarn start as you can see, there is a link tag in the head to reference the CSS file. Changing the content in x. CSS can generate the CSS in real time and then reference it

How do I temporarily generate the schema with the js of Goal 1 during development and with the royalty file of Goal 3 during production builds

Production environment is to run build with Webpack, development is yarn start with serve

The code looks like this

  "scripts": {
    "start": "webpack serve",
    "build": "rm -rf dist  webpack",
    "test": "echo \"Error: no test specified\"  exit 1"
Copy the code

How to do?

Make a copy of webpack.config.js and call it (prod is short for production)

Use: ["style-loader", "css-loader"] instead of the default webpack.config.js for development purposes.

The production environment uses the original use, which can be used for caching. Change mode to production

How do I choose these two files?

Select by command

"scripts": { "start": "webpack serve", "build": "Rm -rf dist  webpack --config",//build with prod configuration "test": "echo \"Error: no test specified\"  exit 1" },Copy the code

After yarn Build, you can see the style tag. Yarn Start can see the link to the CSS in the HTML file

There is only one difference between the two files - eliminating duplicate code with the idea of inheritance

Create a new webpack.config.base.js file

This file copies the shared properties of the two files

You can search webpack Config merge to see how others wrote it, or you can look at my source code - I am also C

The loader and the plugin

Js file through Webpack to get a new JS file, this is through webpack built-in a Babel loader, js loader into webpack, Webpack output another JS file.

What is the difference between webpack Loader and Webpack Plugin

The Webpack Loader is used to load files and the Webpack Plugin is used to extend functionality.

For example, Babel loader is used to load advanced JS and turn it into THE JS supported by IE, CSS loader and Style loader are used to load CSS and turn it into the style tag in the page. Relatively simple function

Plugin can be used to strengthen the webpack function, the function is rich. For example, a plugin called HtmlWebpackPlugin is used to generate HTML files, and a plugin called MiniCssExtractPlugin is used to extract CSS code into a file

Goal 5 -- With WebpackThe introduction of SCSS

  • The main points of

Node-sass is obsolete

Please use the dart - sass

CRM learning Webpack SCSS loader

The installation

yarn add sass-loader dart-sass --dev
Copy the code

Change the CSS suffix to SCSS and then import

Add to webpack.config.base.js.

  module: {
    rules: [
        test: /\.scss$/i,
        use: [
              loader: "sass-loader",
              options: {
                  implementation: require('dart-sass')
Copy the code

Goal 6 -- IntroductionLESS and Stylus

  • experience

SASS, LESS, and Stylus are the same

Change the CSS file suffix to less to become less files (declare variables, reference variables), and reference under the change


@color: red;
    background: @color;
    color: @color;
Copy the code

CRM learning Webpack less Loader

The installation

npm install less less-loader --save-dev
Copy the code

Add the following code to rules by contrast

Module. exports = {module: {rules: [/* here */ {test: /\. Less $/ I, use: [{loader: "style-loader",}, {loader: "CSS - loader"}, {loader: "less - loader", the options: {lessOptions: {strictMath: true,}},},],}, / * * /] here,,}};Copy the code

Create a z.styl file for Stylus (the suffix for Stylus is. Styl)


c = blue;
    background: c;
Copy the code

CRM learn webpack Stylus Loader

The installation

yarn add stylus-loader stylus --dev
Copy the code

Add similar code to webpack.config.base.js rules

module.exports = {
  module: {
    rules: [
        test: /\.styl$/,
        use: [
            loader: "style-loader", // creates style nodes from JS strings
            loader: "css-loader", // translates CSS into CommonJS
            loader: "stylus-loader", // compiles Stylus to CSS
Copy the code

Goal 7 - Use webpackIntroduction of pictures

  • The main points of

Everything has its JS

CRM webpack img loader

Add to rules, if using loader, it is used once per image.

{test: / \. (PNG | SVG | JPG jpeg | | GIF) $/ I use: [" file - loader "] / / the document into a file path / / type: 'asset/resource'},Copy the code


yarn add file-loader --dev
Copy the code

The contents of index.js

Import x from './x.js' import PNG from './assets/1.png' //import PNG will be determined by the loader, the PNG path will have a string of hash console.log(PNG) const div = document.getElementById('app') div.innerHTML = ` img src="${png}" `Copy the code

Target eight -Implementing lazy loading

What is lazy loading? You don't do it when you should, and you do it when you have to.

Why lazy loading? If you load a js file from the beginning, it will take a long time for it to appear, rather than waiting for the user to start a module.

How to implement lazy loading? Import ('xx') to load a XX file, and you'll get a promise. Promise's then will be followed by success and failure.

const button = document.createElement('button')
button.innerText = 'Lazy loading'
button.onclick = () = {
    const promise = import('./lazy')
    promise.then((module) = {
        const fn = module.default()
    },() = {
        console.log('Module loading error')

Copy the code

Configuration complete, CRM learned? This is also my CRM teacher's. There was a version error in my configuration process, and the webpack4 code configured by the teacher was different from the document found by CRM. After several reconfigurations, it was finally ready. I also just started to learn Webpack, which may have many shortcomings, but CRM is ok.

A learning journey for the front end. Email is hope.

Thanks for the advice. Technical rigor is required

About (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.