directory

1 Test the knife

1.1 Creating and initializing a project

1.2 Creating directories and Files

1.3 modify the package. The json

1.4 Write project code

1.5 configuration webpack. Config. Js

1.6 Test Packaging

2 Infrastructure

2.1 To automatically clear dist directory before compilation

2.2 Achieve automatic generation of final HTML from HTML templates

2.3 Building a Project

3. Set up the thermal monitoring server of the development environment

3.1 installation webpack – dev – server

3.2 Use source-map to trace source code errors

4 Separate the configuration files of the production environment and development environment

5 Integrating the Common JS Library (using jQuery as an example)

5.1 Installing and Integrating jQuery

5.2 Applying jQuery globally

5.3 using jQuery

5.4 Pack jQuery Separately

6 Compatible with IE8 processing modes

6.1 Troubleshooting The “Missing Identifier” Error in Internet Explorer 8

6.2 Switching from ES6 to ES5

6.3 Resolving the Error in Internet Explorer 8 that Objects do not support the bind attribute method

Use of the CSS and Stylus

7.1 Loading the CSS and Stylus

7.2 Separating styles into CSS files

7.3 Optimizing the Separation of common CSS Styles

Modularize HTML using EJS

9 Load image resources

9.1 Loading images using the CSS

9.2 HTML loading images

9.3 Troubleshooting the Inconsistency between the Paths of quoted Images in the CSS and HTML

10 load iconfont

11 Use CNPM to speed up download

1 Test the knife

1.1 Creating and initializing a project

Find a directory you like and run the following command:

mkdir webpack-demo
cd webpack-demo
npm init -y
npm install webpack webpack-cli --save-dev
Copy the code

1.2 Creating directories and Files

Note: the “+” at the beginning of each line in the code area of this article means new, “- or D” means deleted, “M” means modified, “…” Represents omission.

Dist is the final compiled production environment code, SRC is the development environment code.

    /- webpack-demo
    |- package.json
+   |- /dist
+      |- index.html
+   |- /src
+      |- index.js
Copy the code

1.3 modify the package. The json

Adjust the package.json file to ensure that our installation package is private and remove the main entry. This prevents accidental releases of your code.

Also add the script command to make executing NPX webpack the same as executing NPM run build.

    "name": "webpack-demo"."version": "1.0.0"."description": "",
+   "private": true,
-   "main": "index.js"."scripts": {-"test": "echo \"Error: no test specified\" && exit 1",
+      "build": "webpack --mode production",
+      "dev": "webpack --mode development"},...Copy the code

1.4 Write project code

Dist /index.html, note the introduction of bundle.js (bundle.js is automatically generated when you package)

<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Webpack Demo</title>
    <script src="bundle.js"></script>
</head>
<body>
</body>
</html>

Copy the code

Write SRC /index.js, whatever you want.

document.write('hello world');
Copy the code

1.5 configuration webpack. Config. Js

The project root directory creates webpack.config.js, which is used to configure webpack.

    |- package.json
    |- /dist
       |- index.html
    |- /src
       |- index.js
+   |- webpack.config.js 
Copy the code

Write a webpack. Config. Js:

const path = require('path'); Module. exports = {// js path entry:'./src/index.js'// Compile the output js and path output: {filename:'bundle.js',
        path: path.resolve(__dirname, 'dist')}};Copy the code

1.6 Test Packaging

NPM run build generates dist as follows:

|-  /dist
    |- index.html
+   |- bundle.js   
Copy the code

The browser runs index.html and displays “Hello World”.

This is the most primitive way to do it. You need to configure HTML in DIST, which is not scientific. What we need to implement is to develop it in SRC and then generate it all in DIST. Please continue to the following chapters.

2 Infrastructure

2.1 To automatically clear dist directory before compilation

Install the clean-webpack-plugin and see 2.3 for the setup code

npm install clean-webpack-plugin --save-dev
Copy the code

2.2 Achieve automatic generation of final HTML from HTML templates

Install html-webpack-plugin and see 2.3 for the setup code

npm install html-webpack-plugin --save-dev
Copy the code

2.3 Building a Project

The build directory is as follows

  |- package.json
  |- webpack.config.js
  |- /dist
  |- /src
     |- /html
        |- index.html
        |- login.html
     |- /js
        |- index.js
        |- login.js 
Copy the code

Rewrite webpack.config.js

const path = require('path');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    // 入口js路径
    entry: {
        index: './src/js/index.js',
        login: './src/js/login.js'}, plugins: [// new CleanWebpackPlugin(), // set the HTML template generation path new HtmlWebpackPlugin({filename:'index.html',
            template: './src/html/index.html',
            chunks: ['index']
        }),
        new HtmlWebpackPlugin({
            filename: 'login.html',
            template: './src/html/login.html',
            chunks: ['login'Output: {// js is generated to dist/js, [name] indicates that the original JS file filename is retained.'js/[name].js'Dist path: path.resolve(__dirname,'dist')}};Copy the code

Now execute NPM run build to generate dist as follows:

 |- /dist
    |- index.html
    |- login.html
    |- /js
       |- index.js
       |- login.js
Copy the code

Look at the HTML code and see that the corresponding JS has been introduced.

3. Set up the thermal monitoring server of the development environment

Now let’s set up a Nodejs-based server, let the code run in the development environment, and implement the automatic hot update of the page when changing the code without refreshing.

3.1 installation webpack – dev – server

Automatically monitors code changes and refreshes the browser in real time

npm install webpack-dev-server --save-dev
Copy the code

Modify the package. The json:

    "scripts": {
        "build": "webpack --mode production",
-       "dev": "webpack --mode development"
+       "serve": "webpack-dev-server --open --mode development"
    },
Copy the code

Modify the webpack. Config. Js:

module.exports = { entry: {... }, + devServer: {+ contentBase:'./dist', + // default 8080, can not write + port: 8080, + // hot update, no need to refresh + hot:true+ }, plugins: [...] . };Copy the code

When you run NPM run serve, a NodeJS Web service is started locally. The browser automatically opens http://localhost:8080/.

Through http://localhost:8080/login.html can access the login page.

If you modify js or HTML files under SRC, the page will be updated automatically.

3.2 Use source-map to trace source code errors

In the dist directory generated by compilation, js code has been re-confused. If there is an error, the error cannot be correctly located to the corresponding position of the original code, which makes it inconvenient to debug the code in the generated environment. If you need to debug your production environment code precisely, you can do so through source-Map. (Skip this section if you don’t need this feature.)

Modify the webpack. Config. Js:

Inline-source-map: Convert the source map to a DataUrl and add it to the js file of the page, resulting in a larger JS file (not recommended).

Source-map: generates the corresponding map file, js is small, but requires the server to set up not to allow access to the map file (recommended)

module.exports = { ... devServer: {... }, + // easy to trace source code error + devtool:'source-map', plugins: [...] . };Copy the code

4 Separate the configuration files of the production environment and development environment

Webpack.config.js includes the configuration of the production environment and the development environment, which is separated to facilitate the maintenance of the code.

Install the WebPack-merge plug-in

Use install Webpack-merge to implement the split.

npm install webpack-merge --save-dev
Copy the code

Split webpack. Config. Js

Create the following three files: Webpack.common.js (common configuration) webpack.dev.js (development environment configuration) webpack.prod.js (production environment configuration) After splitting the webpack.config.js code, you can delete webpack.config.js.

  |- package.json
- |- webpack.config.js
+ |- webpack.common.js
+ |- webpack.dev.js
+ |- webpack.prod.js
  |- /dist
  |- /src
Copy the code

Webpack.common.js keeps the code for the common configuration

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const webpack = require('webpack'); module.exports = { entry: {... }, plugins: [...] , output: {... }};Copy the code

Webpack.dev.js preserves the code configured for the development environment

const merge = require('webpack-merge');
const common = require('./webpack.common'); Module. exports = merge(common, {// devServer: {contentBase:'./dist', // Default port 8080, port: 8080, // hot update, no need to refresh:true}});Copy the code

Webpack.prod.js preserves the code for the production environment configuration

const merge = require('webpack-merge');
const common = require('./webpack.common'); Module. exports = merge(common, {// easy to trace source code errors // (if you don't need trace in section 3.2, you can comment out the underlying code)'source-map'
});
Copy the code

Modify the package. The json:

    "scripts": {
M      "build": "webpack --config webpack.prod.js --mode production",
M      "serve": "webpack-dev-server --open --config webpack.dev.js --mode development"
    },
Copy the code

5 Integrating the Common JS Library (using jQuery as an example)

This section uses jQuery as an example to explain how to introduce the common JS library. You are advised to use the official CLI tool if you use AngularJS, React, or Vue.

5.1 Installing and Integrating jQuery

Install jQuery:

npm install jquery --save
Copy the code

5.2 Applying jQuery globally

JQuery is used on every page, import is too cumbersome on every page, modify webpack.common.js for global configuration:

. + const webpack = require('webpack');

    module.exports = {
        ...
        plugins: [
+           new webpack.ProvidePlugin({
+               $: 'jquery',
+               jQuery: 'jquery'
+           }),
            new CleanWebpackPlugin(),
            ...
Copy the code

5.3 using jQuery

Add div to SRC/HTML /index.html to test:

<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Webpack Demo</title>
</head>
<body>
    <div id="app">
        <div id="info"></div>
    </div>
</body>
</html>
Copy the code

Modify the SRC/js/index. Js:

$('#info').text('jQuery normal use ');
Copy the code

NPM run build generates dist as follows:

| | - / dist | - index. HTML - login. | - HTML/js | - index. Js < - have been integrated into the jQuery code here | - login. JsCopy the code

There is no jQuery code in login.js because jQuery is not currently available in login.js, and the packaging mechanism of Webpack is “actually used” before it is really packaged.

If our project has a lot of static HTML pages, each JS is integrated with jQuery, and the jQuery code is basically unchanged, resulting in redundant JS files, we can package jQuery separately to facilitate browser caching and reduce the requested JS size.

5.4 Pack jQuery Separately

SplitChunks of WebPack are used for separate packaging.

Modify webpack.com mon. Js:

New HtmlWebpackPlugin({filename:'index.html',
            template: './src/html/index.html',
M           chunks: ['jquery'.'index']
        }),
        new HtmlWebpackPlugin({
            filename: 'login.html',
            template: './src/html/login.html',
M           chunks: ['jquery'.'login']
        }),
     ],
+    optimization: {
+       splitChunks: {
+           cacheGroups: {
+               commons: {
+                   test: /jquery/,
+                   name: 'jquery',
+                   chunks: 'all'+} +} +} +}, // compile output configuration output: {... }Copy the code

NPM run build is executed, the page runs normally, and dist is generated as follows:

| | - / dist | - index. HTML - login. | - HTML/js | - index. Js | - login. Js + | - jquery. Js < -- jquery is independenceCopy the code

6 Compatible with IE8 processing modes

To be compatible with browsers of earlier versions such as Internet Explorer 8, using the JS syntax of higher versions such as ES6 during development may cause browsers of earlier versions to fail to run. In addition, you can only use 1.x for jQuery. You need to install a lower version of jQuery. (If IE8 compatibility is not required, skip this section.)

First, install jQuery compatible with IE6 to 8.

npm install jquery-1x --save
Copy the code

Modify webpack.com mon. Js:

. plugins: [ new webpack.ProvidePlugin({ M $:'jquery-1x',
M              jQuery: 'jquery-1x'}),...Copy the code

6.1 Troubleshooting The “Missing Identifier” Error in Internet Explorer 8

Now build code, IE8 will report “missing identifier” in the E. fault code. Uglifyjs-webpack-plugin needs to be installed.

npm install uglifyjs-webpack-plugin --save-dev
Copy the code

Modify webpack.com mon. Js

. + const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

    module.exports = {
        ...
        optimization: {
            splitChunks: { ... },
+           minimizer: [
+               new UglifyJsPlugin({
+                   uglifyOptions: {
+                     ie8: true+} +}) +]},Copy the code

6.2 Switching from ES6 to ES5

If you use ES6 syntax, such as arrow functions, build will fail. To convert ES6 to ES5, you need to install the following plug-ins (many) : babel-loader @babel/core @babel/preset-env @babel/plugin-transform-runtime @babel/plugin-transform-modules-commonjs @babel/runtime

npm install babel-loader @babel/core @babel/preset-env --save-dev
npm install @babel/plugin-transform-runtime @babel/plugin-transform-modules-commonjs --save-dev
npm install @babel/runtime --save
Copy the code

Modify webpack.common.js to convert ES6 to ES5 at compile time:

optimization: {... }, + module: { + rules: [ + { +test: /\.js$/,
+              exclude: /(node_modules|bower_components)/,
+              use: {
+                  loader: 'babel-loader',
+                  options: {
+                      presets: ['@babel/preset-env'],
+                      plugins: [
+                          '@babel/plugin-transform-runtime',
+                          '@babel/plugin-transform-modules-commonjs'+] +} +} +} +] +}, // Compile output configuration output: {... }Copy the code

Now execute NPM run build and the compilation passes. However, IE8 displays an error saying “Objects do not support the bind attribute method”. This is because IE8 does not support ES5, and es5-shim and ES5-SHAM need to be introduced (see the next section).

6.3 Resolving the Error in Internet Explorer 8 that Objects do not support the bind attribute method

Tried a lot of online methods, have not tried success, and finally simply use direct reference method to solve.

Download the plugin

Go to github.com/es-shims/es…

Download es5-shim.min.js and es5-sham.min.js

Create static folder (SRC) to store static resources. Use CopyWebpackPlugin to copy static to dist.

| - / SRC | - (slightly) | | - / HTML/CSS - index. HTML | - login. | - HTML/js (slightly) | - / static | - / js | - es5 - shim. Min. Js | - es5-sham.min.jsCopy the code

Then, directly import SRC/HTML /index.html and SRC/HTML /login. HTML

    <head>
        <meta charset="UTF-8">
        <title>>Webpack Demo</title>
+       <script type="text/javascript" src="static/js/es5-shim.min.js"></script>
    </head>
Copy the code

Es5-sham.min.js can be imported for later use.

Install the copy-webpack-plugin

npm install --save-dev copy-webpack-plugin
Copy the code

Dist (SRC /static); dist (dist);

. + const CopyWebpackPlugin = require('copy-webpack-plugin');
    module.exports = {
        ...
        plugins: [
            ...
            new HtmlWebpackPlugin({
                filename: 'login.html',
                template: './src/html/login.html',
                chunks: ['jquery'.'login']
            }),
+           new CopyWebpackPlugin([
+               { from: './src/static', to: 'static'} +])Copy the code

Execute NPM run build and it will run happily in IE8.

Use of the CSS and Stylus

7.1 Loading the CSS and Stylus

This section uses Stylus as an example. If Sass/Less is used, refer to this method. The purpose of mixing CSS is to learn how to use CSS simultaneously.

Install dependency packages:

npm install style-loader css-loader --save-dev
npm install stylus-loader stylus --save-dev
Copy the code

Now the SRC directory looks like this:

+ | | - / SRC/CSS + + | | - / common - common. CSS + | - frame. CSS (this file @ import. Common CSS and reset CSS) + | - reset. CSS + | - / pages + | - index. Styl + | - login. Styl | | - / HTML - index. | | - login. HTML HTML - / js (abbreviated)Copy the code

Style code in CSS and STYl, please supplement, not shown here.

Introducing styles in index.js:

import '.. /css/common/frame.css';
import '.. /css/pages/index.styl';
Copy the code

Introducing styles in login.js:

import '.. /css/common/frame.css';
import '.. /css/pages/login.styl';
Copy the code

Modify webpack.com mon. Js:

    module.exports = {
        ...
        optimization: { ... }
+       module: {
+           rules: [
+              {
+                  test: /\.css$/,
+                  use: [
+                      'style-loader',
+                      'css-loader'+] +}, + {+test: /\.styl$/,
+                  use: [
+                      'style-loader',
+                      'css-loader',
+                      'stylus-loader'+] +} +] +},...Copy the code

After executing build, the style code is packaged and inserted directly into the HTML file.

7.2 Separating styles into CSS files

Now we want to introduce styles via link.

Install MiniCssExtractPlugin first

npm install mini-css-extract-plugin --save-dev
Copy the code

Then modify webpack.common.js

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

    module.exports = {
        plugins: [
           ...
+          new MiniCssExtractPlugin({
+              filename: 'css/[name].css'
+          }),
            new CopyWebpackPlugin([
                { from: './src/static', to: 'static' }
            ])
        ],
        module: {
            rules: [
                {
                    test: / \. CSS $/, use: [+ / / replace the original style - loader M MiniCssExtractPlugin loader,'css-loader'] {},test: / \. Styl $/, use: [+ / / replace the original style - loader M MiniCssExtractPlugin loader,'css-loader'.'stylus-loader'...]}Copy the code

NPM run build generates dist as follows:

| | - / dist | - index. HTML - login. HTML + + | | - / CSS - index. CSS + | - login. | - CSS/js (abbreviated)Copy the code

CSS index. CSS and login. CSS both contain common styles and can be further optimized to separate them out.

7.3 Optimizing the Separation of common CSS Styles

Modify webpack.common.js to use regex to package and reference CSS in SRC/CSS /common/ separately.

. plugins: [ new HtmlWebpackPlugin({ filename:'index.html',
            template: './src/html/index.html',
M           chunks: ['style'.'jquery'.'index']
        }),
        new HtmlWebpackPlugin({
            filename: 'login.html',
            template: './src/html/login.html',
M           chunks: ['style'.'jquery'.'login']
        }),
        new MiniCssExtractPlugin({
            filename: 'css/[name].css'
        })
    ],
    optimization: {
        splitChunks: {
            cacheGroups: {
                commons: {
                    test: /jquery/,
                    name: 'jquery',
                    chunks: 'all'
                },
+               styles: {
+                   test: /[\\/]common[\\/].+\.css$/,
+                   name: 'style',
+                   chunks: 'all',
+                   enforce: true+}}}},Copy the code

NPM run build generates dist as follows:

| | - / dist | - index. HTML - login. HTML + + | | - / CSS - index. CSS + | - login. CSS | - style. CSS < - | - common CSS/js | - index. Js | - login. Js | - jquery. Js | - style. Js < -- how can have this?Copy the code

Found that an extra style.js was generated in the dist/js/ directory, and the HTML referenced the extra JS. This is a bug in webpack4, which has been in open state since 2016. Third-party plug-ins have tried it, but it has not been solved yet, and we expect it to be solved in webpack5.

See: github.com/webpack/web…

Third-party plug-ins involved in online solutions:

disable-output-webpack-plugin

html-webpack-exclude-assets-plugin

remove-source-webpack-plugin

The above plug-ins have not been updated for a long time and are not available in the latest Webpackage 4.35.0.

Modularize HTML using EJS

If every page has a header, you can split the header into HTML modules and import it on the pages you want. This is done through EJS. Ejs is essentially HTML, but with more template syntax.

Install the ejs – loader

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

For example, rename index.html to index.ejs

Modify webpack.common.js to support EJS:

    plugins: [
          ...
            new HtmlWebpackPlugin({
                filename: 'index.html'+ // change HTML to ejs M template:'./src/html/index.ejs',
                chunks: ['style'.'jquery'.'index']}),... module: { rules: [ ... + { +test: /\.ejs/,
+                   use: ['ejs-loader'] +}...Copy the code

Create/components/headers/SRC/HTML header. The ejs

<div id="header" class="G-header"> This is the public header </div>Copy the code

SRC/HTML /index.ejs.

. <div id="app">
+       <%= require('./components/header/header.ejs')() %>
        <div id="info"></div>
    </div>
    ...
Copy the code

9 Load image resources

This section describes how to reference images in CSS and HTML.

Install file-loader and url-loader. Url-loader is based on file-loader, so install both. (You can also use only file-loader. Url-loader extends functions on the basis of file-loader, such as setting the base64 transcoding of images smaller than the number of KB).

npm install file-loader url-loader --save-dev
Copy the code

9.1 Loading images using the CSS

Modify webpack.com mon. Js

    module: {
        rules: [
            ...
+           {
+              test: /\.(png|svg|jpg|gif|webp)$/,
+              use: [
+                  {
+                      loader: 'url-loader', + options: {+ // In the final generated CSS code, the image URL prefix + publicPath:'.. /images', + // The actual path of image output (relative to dist) + outputPath:'images', + // Changes to Base64 + when the value is smaller than a certain KBlimit: 0 +} +} +] +}... ] },Copy the code

Add the image 1.jpg to SRC /images

| - / SRC (slightly) | - | - / CSS/HTML (slightly) + + | | - / images - 1. JPG | - / js (slightly) | - / static (abbreviated)Copy the code

Add code to SRC/CSS /pages/index.styl:

.bg-pic width: 200px height: 200px background: url(.. /.. /images/1.jpg) no-repeatCopy the code

Add code to SRC/HTML /index.ejs:

    <div id="app">
        <%= require('./components/header/header.ejs')() %>
        <div id="info"></div>
+       <div class="bg-pic"></div>
    </div>
Copy the code

After NPM run build is executed, the images can be accessed normally, and the dist directory is generated as follows:

| - / dist (slightly) | - | - / CSS/images + | - f0a89ff457b237711f8306a000204128. JPG | - / js (slightly) | - / static (slightly) | - index. | - HTML login.htmlCopy the code

9.2 HTML loading images

Img is used to load images in HTML. The address of images in HTML needs to be extracted and the htML-loader plug-in needs to be installed

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

Add image 2.jpg to SRC /images

| - / SRC (slightly) | - | - / CSS/HTML (slightly) | | - 1. - / images JPG + | 2. JPG | - / js (slightly) | - / static (abbreviated)Copy the code

Modify webpack.common.js to extract and package images from HTML.

    module: {
        rules: [
            ...
+           {
+              test: /\.(html)$/,
+              use: {
+                  loader: 'html-loader',
+                  options: {
+                      attrs: ['img:src'.'img:data-src'.'audio:src'],
+                      minimize: true+} +} +}...Copy the code

Add code to SRC/HTML /index.ejs:

    <div id="app">
        <%= require('./components/header/header.ejs')() %>
        <div id="info"></div>
        <div class="bg-pic"></div>
+       <img src="${require('.. /images/2.jpg')}" alt="">
    </div>
Copy the code

After NPM run build is executed, the image can be accessed normally and the dist directory is generated as follows

| - / dist (slightly) | - | - / CSS/images | - f0a89ff457b237711f8306a000204128. JPG + | - dab63db25d48455007edc5d81c476076. JPG | - / js (abbreviated) | - / static (slightly) | - index. | - login HTML. HTMLCopy the code

However, img images in HTML cannot be displayed. Looking at the generated code:

Dist/index. In the HTMLThe SRC for.. /images/xxxx.jpg

Dist/CSS /index.css background url is also.. /images/xxxx.jpg

Because the paths of HTML and CSS are one level different, the paths are inconsistent. So you need to distinguish between image paths in HTML and CSS.

9.3 Troubleshooting the Inconsistency between the Paths of quoted Images in the CSS and HTML

Will modify webpack.com mon. Js, MiniCssExtractPlugin. The loader to the object:

    module: {
        rules: [
            ...
            {
                test: / \. CSS $/, use: [M {M loader: MiniCssExtractPlugin loader, M options: {M / / CSS image path in the add prefix M publicPath:'.. / '
M                      }
M                  },
                'css-loader'] {},test: / \. Styl $/, use: [M {M loader: MiniCssExtractPlugin loader, M options: {M / / CSS image path in the add prefix M publicPath:'.. / '
M                      }
M                  },
                    'css-loader'.'stylus-loader']},... {test: /\.(png|svg|jpg|gif|webp)$/,
                use: [
                    {
                        loader: 'url-loader', options: {D // Final generated image path code (delete) D // publicPath:'.. /images'// the actual outputPath of the image outputPath:'images', // Change to Base64 when the value is smaller than a certain KBlimit: 0}}]},...Copy the code

Then run NPM run build, the path is displayed normally.

10 load iconfont

Download font and style files from Alibaba icon website www.iconfont.cn/ and import them into the project. The structure is as follows:

|- /src |- /css |- /common |- common.css |- frame.css + |- iconfont.css |- reset.css |- /pages |- index.styl |- login.styl + |- /fonts + |- iconfont.eot + |- iconfont.svg + |- iconfont.ttf + |- iconfont.woff + |- iconfont.woff2 |- / HTML (slightly) (slightly) | - | - / images/js (slightly) | - / static (abbreviated)Copy the code

SRC/CSS /common/frame. CSS @import “iconfont. CSS “, then modify the path of each font in iconfont.

Use the font directly in SRC/HTML /index.ejs (the font style is defined at iconfont) :

<i class="G-iconfont G-ficon-cart"></i>
Copy the code

Modify webpack.com mon. Js,

    module: {
        rules: [
            ...
+          {
+              test: /\.(woff|woff2|eot|ttf|svg)$/,
+              use: {
+                  loader: 'file-loader', + options: {+ // keep the original filename and suffix + name:'[name].[ext]', + // output to dist/fonts/ directory + outputPath:'fonts', +} +} +}]},Copy the code

NPM run build generates the dist directory as follows:

| - / dist (slightly) | - | - / CSS/images (slightly) + | - / fonts. | - iconfont eot | - iconfont. SVG | - iconfont. The vera.ttf | - iconfont. Woff | - / js (abbreviated) | - / static (slightly) | - index. | - login HTML. HTMLCopy the code

The woff2 file is not generated because there are no references in the CSS.

11 Use CNPM to speed up download

NPM sometimes download speed is very slow, you can install CNPM, download from domestic Taobao image, execute the following command:

npm install -g cnpm --registry=https://registry.npm.taobao.org
Copy the code

In the future, NPM is directly replaced with CNPM.

The above is the technology sharing of building standard front-end engineering based on Webpack 4.x.

Please follow my personal wechat official number to get the latest articles ^_^