Due to the needs of the project, use Webpack to build an environment for common functions. The initial functions are listed as follows: Automatic configuration multi-entry exit LESS to CSS CSS prefix automatic complement CSS extract to a single file CSS compression image compression import font and SVG JS Babel compression SEPARATION/merger and filtering of CSS and JS

1. Create and access the folder

The mkdir webpack4.29.6 &&cd webpack4.29.6
Copy the code

2. Create demo files and pictures as shown below

index.html:

<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>test</title> </head> <body> Write some random index2333 </body> </ HTML >Copy the code
<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>test</title> </head> <body>Copy the code

Other files can be left empty and images can not be imported.

3. Create package.json(all commands below are run in webPack4.29.6)

npm init -y
Copy the code

4. Install the following dependencies

(Webpack/webpack-CLI are two important things to note,3.x previous versions are merged together, 4.x after the split webpack-dev-server: service, HTML -webpack-plugin: dynamic generation of HTML webpack-merge: webpack configuration file)

npm install -D webpack webpack-cli webpack-dev-server html-webpack-plugin webpack-merge
Copy the code

Make sure both the local and global dependency versions are up to date as shown below (see webpack is 4.29.6 if you install 3 because of network issues). A few, will be all error later. This step is very important, otherwise you will have no end of trouble, if it is not successful, you can first delete the webpack related Files under the global node,window in c disk /Program Files/nodejs/).

5. Create three webpack configuration texts (1.common2.dev3.prod) and write them separately

touch webpack.common.js webpack.dev.js webpack.prod.js
Copy the code

webpack.common.js:

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: {
    index: "./src/js/index.js"}, output: {//[name] Output name equals input name [contenthash:8] eight bitshash
    filename: "[name].[contenthash:8].js", / / you should know the node in the path of knowledge: http://nodejs.cn/api/path.html path: the path. The resolve (__dirname,"dist")
  },
  module: {
    rules: [
    
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: "index.html",
      template: "./src/index.html"}})];Copy the code

webpack.dev.js:

const merge = require("webpack-merge");
const common = require("./webpack.common.js");

module.exports = merge(common, {
  mode: "development"// Start devTool:"source-map", devServer: {// Set basic directory structure contentBase:"./dist"// The server IP address can be used as IP or localhost host:"localhost"// Whether compress is enabled on the server:true// Configure the service port number port: 8090}});Copy the code

webpack.prod.js:

const merge = require("webpack-merge");
const common = require("./webpack.common.js");

module.exports = merge(common, {
  mode: "production"});Copy the code

6. Modify the Script object in package.json

  "scripts": {
    "dev": "webpack-dev-server --config webpack.dev.js"."build": "rimraf dist && webpack --config webpack.prod.js"
  },
Copy the code

7. Try to start the service or package it

Start the service:

npm run dev
Copy the code

Packing: (Rimraf dist: Delete rimraf folder before packing and rebuild)

npm run build
Copy the code

dist:

Since it is troublesome to restart the service every step after modifying the configuration file, we introduce Nodemon here. And add a command

npm install -D nodemon
Copy the code

// Listen for webpack.common.js and restart NPM run dev if there are changes

"startdev": "nodemon --watch webpack.common.js --exec  npm run dev "
Copy the code

package.json:

The system starts to configure common project functions

You can see that the file image in the previous package is only typed as index.html. Here is how to introduce multiple HTML

Webpack.common.js: Add one more about.js and one more instance of the plugin to the entry:


multi.page.js:

// const path = require("path");
const fs = require("fs");
const htmlWebpackPlugin = require("html-webpack-plugin");
const pagesPath = path.resolve("./src");

var pageList = [];
function readPages() {
  fs.readdirSync(pagesPath).forEach(e => {
    var fullPath = pagesPath + "/" + e;
    if (e.includes("html")) {
      var baseName = e.slice(0, e.indexOf("."));
      pageList.push({
        entry: pagesPath + "\\js\\" + baseName + ".js",
        chunkName: baseName,
        template: pagesPath +'\ \'+ e }); }});returnpageList; } // exports. GetEntryPages =function() {
  return readPages().reduce((r, page) => {
    r[page.chunkName] = page.entry;
    returnr; }, {}); }; // exports.htmlplugins =function() {
  var list = readPages().map(page => {
    var options = {
      filename: page.chunkName + ".html",
      template: page.template,
      chunks: [page.chunkName]
    };
    return new htmlWebpackPlugin(options);
  });
  return list;
};

Copy the code

webpack.common.js:

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const multiPage = require("./multi.page");

module.exports = {
  //   entry: {
  //     index: "./src/js/index.js",
  //     about: "./src/js/about.js"//}, entry: multipage.getentrypages (), Output: {//[name] The output name equals the input name [contenthash:8]hash
    filename: "[name].[contenthash:8].js", / / you should know the node in the path of knowledge: http://nodejs.cn/api/path.html path: the path. The resolve (__dirname,"dist")
  },
  module: {
    rules: []
  },
  plugins: [
    // new HtmlWebpackPlugin({
    //   filename: "index.html",
    //   template: "./src/index.html"
    // }),
    // new HtmlWebpackPlugin({
    //   filename: "about.html",
    //   template: "./src/about.html"
    // })
    ...multiPage.htmlPlugins()
  ]
};

Copy the code

Is to improve the manual import export to nodeJS automatic traversal

We will write the common functions in webpack.common.js for debugging purposes, and then switch to webpack.dev.js or webpack.prod.js as needed

Working with CSS (I’m using less as an example here) install the following dependencies

npm install -D css-loader style-loader less less-loader 
Copy the code

Modify webpack.com mon. Js:

  module: {
    rules: [
      {
        test: /\.less$/,
        use: ["style-loader"."css-loader"."less-loader"],
        include: path.resolve(__dirname, "./src") // Specify a path to improve performance}]},Copy the code

Modify index.js to introduce index.less, and write arbitrary styles

index.html

<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>test</title>
</head>
<body>
    <div class="test"</div> </body> </ HTML >Copy the code

index.js:

import index from ".. /css/index.less";
Copy the code

index.less

body {
  display: flex;
  background: # 666;
  .test {
    color: #ff0; }}Copy the code

You will find that the relevant style is in the head style, and then optimize a step, to extract the style to install the mini-css-extract-plugin

npm install -D mini-css-extract-plugin
Copy the code

Webpack.common.js imports dependencies, modifies rules, and outputs

webpack.common.js:

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const multiPage = require("./multi.page");
const MiniCssExtractPlugin = require("mini-css-extract-plugin"); Module.exports = {// entry: {// index: {// export: {// export: {// export: {// export: {// export: {// export: {// export: {"./src/js/index.js",
  //     about: "./src/js/about.js"//}, entry: multipage.getentrypages (), Output: {//[name] The output name equals the input name [contenthash:8]hash
    filename: "[name].[contenthash:8].js", / / you should know the node in the path of knowledge: http://nodejs.cn/api/path.html path: the path. The resolve (__dirname,"dist")
  },
  module: {
    rules: [
      {
        test: /\.less$/,
        // use: ["style-loader"."css-loader"."less-loader"],
        use: [MiniCssExtractPlugin.loader, "css-loader"."less-loader"],
        include: path.resolve(__dirname, "./src"}]}, plugins: [// new HtmlWebpackPlugin({// filename:"index.html",
    //   template: "./src/index.html"
    // }),
    // new HtmlWebpackPlugin({
    //   filename: "about.html",
    //   template: "./src/about.html"
    // })
    ...multiPage.htmlPlugins(),
    new MiniCssExtractPlugin({
      filename: "css/[name].[contenthash:8].css"}})];Copy the code

Continue to optimize CSS prefixes automatically

Install dependencies:

npm install -D postcss-loader autoprefixer
Copy the code

Modify the package. The json:

  "browserslist": [
    "1%" >."last 2 versions"."not ie <= 8"
  ]
Copy the code

Modify webpack.com mon. Js:

--- use: [MiniCssExtractPlugin.loader, "css-loader"."less-loader"],
+++  use: [
          MiniCssExtractPlugin.loader,
          "css-loader",
          {
            loader: "postcss-loader",
            options: {
              plugins: () => [require("autoprefixer") (the)]}},"less-loader"].Copy the code

Finally, compress the CSS file

Install dependencies:

npm install -D optimize-css-assets-webpack-plugin
Copy the code

Modify webpack.com mon. Js:

const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin')


new OptimizeCssAssetsPlugin({
    assetNameRegExp: /\.css$/g, 
    cssProcessor: require('cssnano'), // CSS processor for optimizing/minimizing CSS, default to cssnano cssProcessorOptions: {safe:true, discardComments: { removeAll: true}}, // Options passed to cssProcessor, default is {} canPrint:true// A Boolean value indicating whether the plug-in can print messages to the console, defaulttrue
}),
Copy the code

Take a look at the resulting source file:

Import images and compress them

npm install -D css-loader file-loader html-withimg-loader image-webpack-loader
Copy the code

webpack.common.js:

{
        test: /\.(svg|png|jpe? g|gif)$/i, use: [ { loader:"url-loader",
            options: {
              limit: 1,
              name: "images/[name].[contenthash:8].[ext]",
              publicPath: ".. /"}}, {loader:"image-webpack-loader",
            options: {
              pngquant: {
                quality: "70-80",
                speed: 1
              }
            }
          }
        ]
      },
      {
        test: /\.html$/,
        use:[
            'html-withimg-loader']}Copy the code

The introduction of the font

Modify webpack.com mon. Js:

      {
        test: /\.(woff|woff2|eot|ttf|otf)$/,
        use: [
          {
            loader: "file-loader",
            options: {
              name: "assets/[name].[contenthash:8].[ext]",
              publicPath: ".. /"}}}]Copy the code

Babel upgrade is a little gross.. I don’t want to say that we’ll do extraction and merge filtering of CSS and JS based on the project

from:webpack.docschina.org/api/