webpack4.x study notes

If there is input, there must be output. Today, let's output the process of learning webpack.

I have to complain first. Compared with cute grunt and easy-to-use gulp, I really can't love webpack!

There is also a bloody lesson: don't be lazy, go directly to the official website if you have any questions. . .

This article aims to record the driving and problems encountered in learning webpack. It is suitable for developers who have some basic knowledge of node and webpack, and will not record the operation commands in detail. There are still some problems that are unsolved, and experts are also invited to advise.

First, paste the versions of various packages when building. After all, the compatibility of webpack is not very good every time it is upgraded.

OS: windows 10; node: v8.9.4

Building steps

1. Install webpack, webpack-cli, webpack-dev-server html-webpack-server ( webpack-cli has been removed in the 4.x version, and needs to be installed here );

   Corresponding configuration: 

      a. Configure the command to start the server in the scripts of package.json.

   

      b. Configure the entry, exit, and server in webpack.config.js;

         For more configuration parameters of server, please refer to https://webpack.js.org/configuration/dev-server/#src/components/Sidebar/Sidebar.jsx

      c. Configure html-webpack-plugin, automatically generate an html in the compiled folder, and have added the compiled entry js;

  After configuration webpack.config.js: (At this time we can directly use  npm run dev  to start the service.)

const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry:{ // Entry file, where multiple entries can be configured 
        main: path.resolve(__dirname,'src/module/index/main.js' ),
         ​​// plugin: path.resolve(__dirname,'src/plugin/ plugin.js') 
    },
    output: { // The file location and file name after packaging 
        path: path.resolve(__dirname,'dist' ),
        filename: '[name].js' 
    },
    devServer: { // server configuration 
        contentBase: path.join(__dirname,"dist"), // the folder pointed to by the service 
        port: 9000, // the port number 
        inline: true , // the automatic refresh mode is configured as inline 
        open: true , // Whether to automatically open the page 
        proxy: { // Proxy configuration 
            "/dist" : {
                target: "http://localhost:3000",
                pathRewrite: {
                    "^/api": ""
                },
                bypass: function (req, res, proxyOptions){
                     // proxy filter function 
                    return ""
                }
            }
        }
    },
    plugins: [
        new HtmlWebpackPlugin({
             // Configure the source html template for generating new html 
            template: path.resolve(__dirname,'src/index.html' )
        })
    ]
}

 

2. Configure the loader

  a. Install the js processing package: babel-loader babel-ccore babel-preset-env and configure

    babel-preset-env can compile only those features that are not supported according to the configured env. For details, please refer to https://github.com/babel/babel-preset-env

{
    test: /\.js$/,
    use: {
        loader: 'babel-loader',
        options: {
            presets: ['env'],
            cacheDirectory: true  // Configure allows caching to speed up compilation 
        }
    }
}

  b. Install the css processing package node-sass sass-loader (sass is used in the code, the configuration of less is the same as that of sass, just install the processing plug-in corresponding to less)

     Install the css separation processing plugin extract-webpack-text-plugin, extract the css style from the html page and put it into a separate file

     sass-loader depends on node-sass, so don't forget to install node-sass here ;

    First, extract-webpack-text-plugin is introduced, and two new objects are created to process css and less respectively, and the parameters are passed as the saving path of the processed style:

const ExtractTextPlugin = require("extract-text-webpack-plugin");

const extractCss = new ExtractTextPlugin('css/[name].css');
const extractLess = new ExtractTextPlugin('css/[name].css');

 

   The rules for configuring the loader in the module:

{
    test: /\.scss$/,
    use: extractLess.extract(["css-loader","sass-loader"])
},
{
    test: /\.css$/,
    use: extractCss.extract({
         fallback: "style-loader",
          use: "css-loader"
    })
},

 

   Add extractCss and extractLess plugins to plugins:

plugins: [
    new HtmlWebpackPlugin({
        template: path.resolve(__dirname,'src/index.html')
    }),
    extractCss,
    extractLess
]

 

  c, img, font and other file loader installation and configuration url-loader file-loader

   Note: The document describes that url-loader is a loader that supports more configurations based on file-loader encapsulation, but after testing, it is found that url-loader cannot be used alone, and file-loader needs to be installed at the same time.

      If anyone knows the reason, please leave a message, thanks in advance!

{ // Load image loader configuration 
    test: /\.(png|jpg|gif)$/ ,
        use: [
        {
            loader: 'url-loader',
            options: {
              limit: 8192 // size limit 
            }
        }
    ]
},
{ // Load font and other loader configuration 
    test: /\.(eot|svg|ttf|woff|woff2)(\?\S*)?$/ ,
    use:{
        loader: 'file-loader'
    }
}

 3. Other plugin configuration

  uglifyJsPlugin, this plugin has also been independent in the 4.x version and needs to be installed separately to use.

  Regarding the activation of module hot loading, various implementations are given in the official documents. Here is the test using the devServer implementation method:

  For other implementation details, please refer to https://doc.webpack-china.org/guides/hot-module-replacement

  Set hot: true in devServer and add webpack.HotModuleReplacementPlugin(); in plugins

  Test Results:

      Modify the html file: the browser displays a prompt of the word HMR, but the page has not changed:

      Modify the js file: the page is completely refreshed after compilation;

When I was going to continue to configure multiple entries and multiple pages, I found that I could only call html-webpack-plugin in a loop to generate html;

So far, webpack has given me the impression that the compilation speed is slow, the documentation is not clear, and there are strange bugs one after another. These feelings are probably because the learning is not in-depth and detailed enough.

Finally, post package.json and webpack.config.js

{
  "name": "webpackOnly",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack-dev-server"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.4",
    "babel-preset-env": "^1.6.1",
    "css-loader": "^0.28.11",
    "extract-text-webpack-plugin": "^4.0.0-beta.0",
    "file-loader": "^1.1.11",
    "html-webpack-plugin": "^3.2.0",
    "node-sass": "^4.8.3",
    "sass-loader": "^7.0.1",
    "style-loader": "^0.21.0",
    "uglifyjs-webpack-plugin": "^1.2.5",
    "url-loader": "^1.0.1",
    "webpack": "^4.6.0",
    "webpack-cli": "^2.0.15",
    "webpack-dev-server": "^3.1.3"
  },
  "dependencies": {
    "element-ui": "^2.3.6"
  }
}
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const extractCss = new ExtractTextPlugin('css/[name].css');
const extractLess = new ExtractTextPlugin('css/[name].css');

module.exports = {
    entry:{ // Entry file, where multiple entries can be configured 
        main: path.resolve(__dirname,'src/module/index/main.js' ),
        plugin: path.resolve(__dirname,'src/plugin/plugin.js')
    },
    output: { // The file location and file name after packaging 
        path: path.resolve(__dirname,'dist' ),
        filename: '[name].js' 
    },
    devServer: { // server configuration 
        contentBase: path.join(__dirname,"dist"), // the folder pointed to by the service 
        port: 9000, // the port number 
        inline: true , // the automatic refresh mode is configured as inline 
        open: true , // Whether to automatically open the page 
        hot: true ,
        proxy: { // Proxy configuration 
            "/dist" : {
                target: "http://localhost:3000",
                pathRewrite: {
                    "^/api": ""
                },
                bypass: function (req, res, proxyOptions){
                     // proxy filter function 
                    return ""
                }
            }
        }
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: path.resolve(__dirname,'src/index.html')
        }),
        new UglifyJsPlugin({
            uglifyOptions: {
                compress: false
            }
        }),
        new webpack.HotModuleReplacementPlugin(), // hot loading plugin 
        extractCss,
        extractLess
    ],
    module: {
        rules: [
            {
                test: /\.js$/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['env'],
                        cacheDirectory: true  // Configure allows caching to speed up compilation 
                    }
                }
            },
            {
                test: /\.scss$/,
                use: extractLess.extract([ "css-loader","sass-loader" ])
                 /* use: [{ //Do not use css extraction configuration
                    loader: 'style-loader'
                },{
                    loader: 'css-loader'
                },{
                    loader: 'sass-loader',
                    options: {
                        includePaths: ["src"]
                    }
                }]*/
            },
            {
                test: /\.css$/,
                use: extractCss.extract({
                     fallback: "style-loader",
                      use: "css-loader"
                })
            },
            {
                test: /\.(png|jpg|gif)$/,
                use: [
                    {
                        loader: 'url-loader',
                        options: {
                          limit: 8192
                        }
                    }
                ]
            },
            {
                test: /\.(eot|svg|ttf|woff|woff2)(\?\S*)?$/,
                use:{
                    loader: 'file-loader'
                }
            }
        ]
    }
}

 

 

   

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324922901&siteId=291194637