Introduction and basic configuration of webpack

Posted by phpCCore Brad on Sat, 15 Jun 2019 23:29:00 +0200

webpack installation and command line

First step initialization (I use Taobao mirror cnpm here)

cnpm init

Step 2 Install webpack

cnpm install webpack --save-dev

The third step is to install the loader that handles css

cnpm instal css-loader style-loader --save-dev

The fourth step is to introduce other files into hello.js, which serves as the entry point for packaging.

require('./world.js');
require('style-loader!css-loader!./style.css');
/*
The loader here can also be written directly from the command line, i.e.
webpack hello.js hello.bundle.js --module-bind 'css=style-loader!css-loader'
The parameter "--module-bind" of webpack is used.
*/

Step 5 Packing multiple files into hello.bundle.js

webpack hello.js hello.bundle.js

Some parameters

  • Observation File Change, Automatic Packing--watch
    webpack hello.js hello.bundle.js --watch

  • Packing Percentage Reader--progress
    webpack hello.js hello.bundle.js --progress

  • Display packaged module loader --display-modules
    webpack hello.js hello.bundle.js --progress --display-modules

  • Packing Reasons--display-reasons
    webpack hello.js hello.bundle.js --progress --display-modules --display-reasons

Basic configuration of Web pack

New configuration file webpack.config.js

module.exports = {
    entry: './src/js/main.js',
    output: {
        path: './dist/js',
        filename: 'bundle.js'
    }
}

Entering webpack in the console will execute the script by default, or you can specify -- config to select the script

entry entries can be either single or multiple, and multiple entries need to be packaged in different js.

[hash] is the hash packaged this time;
[chunkhash] is the hash of each file, which changes only when the content of the file changes.

Generate html pages in projects

First install the html-webpack-plugin plug-in: cnpm install html-webpack-plugin --save-dev

How to use it

//First introduce
var htmlWebpackPlugin = require('html-webpack-plugin');

plugins: [
        new htmlWebpackPlugin({
            template: 'index.html', //Generate pages using this as a template
            // Filename:'index - [hash]. html', // Specify a name for the generated HTML file
            filename: 'index.html',
            inject: false, //Specify whether js is inserted in the head or body tag, default is the body tail, not inserted when changed to false
            title: 'webpack is good', //Set properties for calling in templates
            date: new Date(),
            minify: {
                removeComments: true, // Delete Note
                collapseWhitespace: true // Delete blanks
            }
        })
    ]

Support ejs template syntax and use it directly in html

<head>
    <meta charset="UTF-8">
    <!--In this case, we call the ____________ webpack.config.js Inside the settings of the ____________ title-->
    <title><%= htmlWebpackPlugin.options.title %></title>

    <script type="text/javascript" src="<%= htmlWebpackPlugin.files.chunks.main.entry %>"></script>

</head>

<body>
    <% for (var key in htmlWebpackPlugin) { %>
        <%= key %>
    <% } %>
</body>

Generate multiple pages

Use new HTML Web pack Plugin () several times and configure the relevant parameters.

        new htmlWebpackPlugin({
            template: 'index.html',
            filename: 'b.html',
            inject: 'body',
            title: 'this is b',
            // chunks: ['b'], // Specify the js to be included for the page
            excludeChunks: ['a', 'c'] //Specify js to exclude for this page
        }),
        new htmlWebpackPlugin({
            template: 'index.html',
            filename: 'c.html',
            inject: 'body',
            title: 'this is c',
            // chunks: ['c'],
            excludeChunks: ['a', 'b']
        })

Insert js directly into the page

<%= compilation.assets[htmlWebpackPlugin.files.chunks.main.entry.substr(htmlWebpackPlugin.files.publicPath.length)].source() %>

Processing resource files in projects

What is loader

Tools for processing resource files,
Features: 1. It can be in series, 2. It can be synchronous or asynchronous, 3. It can accept parameters, 4. It can specify the type of file to be processed through regular expressions, and so on.

Transfer parameters:
You can use require: require("url-loader?minetype=image/png!./file.png")
You can also add query to the configuration file

{
    test: /\.png$/,
    loader: "url-loader",
    query: { mimetype: "image/png" }
}

Note: The latest version of webpack does not allow the abbreviation loader, so "-loader" must be added.

Converting ES6 with babel-loader

Install babel-loader and babel-core
cnpm install babel-loader babel-core babel-preset-latest --save-dev

How to specify presets (alternative):
1. Can be configured in webpack.config.js

        loaders: [
            {
                test: /\.js$/,
                loader: 'babel',
                query: {
                    presets: ['latest'] // Tell babel how to deal with our ES6, which version of the ES6 rule to deal with, where lastest is all versions
                }
            }
        ]
  1. babel configuration files (. babelrc) can be created in the project's root directory
    .babelrc
{
    "presets": ["latest"]
}
  1. Configure directly in package.json
{
  "name": "webpack-study",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "babel": {
    "presets": ["latest"]
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "webpack": "webpack --config webpack.config.js --progress --display-modules --colors --display-reasons"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.24.0",
    "babel-loader": "^6.4.1",
    "babel-preset-latest": "^6.24.0",
    "css-loader": "^0.27.3",
    "html-webpack-plugin": "^2.28.0",
    "style-loader": "^0.15.0",
    "webpack": "^2.2.1"
  }
}

Here we decide to choose the first one.

Increase packing speed:

exclude: './node_modules/', // Do not process ES6 files in this folder, that is, specify the range of unpackaged files
include: path.resolve(__dirname, 'src/'), // To specify the scope of the package, it must be an absolute path

Using css-loader to process CSS

Install css-loader and style-loader
cnpm install css-loader style-loader --save-dev

Automatically adding prefixes
cnpm install postcss-loader autoprefixer --save-dev

Processing @import in css
cnpm install postcss-import --save-dev

To configure

{
    test: /\.css$/,
    use: ['style-loader', 'css-loader?importLoaders=1', {
        loader: 'postcss-loader',
        options: {
            plugins: function () {
                return [
                    require('postcss-import'), // Processing @import in css
                    require('autoprefixer')  // Automatically add browser prefix
                ];
            }
        }
    }]
}

Using less-loader to process less

Install less and less-loader
cnpm install less less-loader --save-dev

To configure

{
    test: /\.css$/,
    use: ['style-loader', 'css-loader?importLoaders=1', {
        loader: 'postcss-loader',
        options: {
            plugins: function () {
                return [
                    require('postcss-import'), // Processing @import in css
                    require('autoprefixer')  // Automatically add browser prefix
                ];
            }
        }
    }, 'less-loader']
}

Using sass-loader to process scss

Install node-sass and sass-loader
cnpm install node-sass sass-loader --save-dev

To configure

{
    test: /\.sass$/,
    use: ['style-loader', 'css-loader?importLoaders=1', {
        loader: 'postcss-loader',
        options: {
            plugins: function () {
                return [
                    require('postcss-import'), // Processing @import in css
                    require('autoprefixer')  // Automatically add browser prefix
                ];
            }
        }
    }, 'sass-loader']
}

Processing template files

Install html-loader
cnpm install html-loader ejs-loader --save-dev

To configure

{
    test: /\.html$/,
    loader: "html-loader"
},
{
    // test: /\.ejs$/,
    test: /\.tpl$/,
    loader: "ejs-loader"
}

Processing pictures and other documents

Install file-loader
cnpm install file-loader url-loader image-webpack-loader --save-dev

How to Refer to Pictures in Templates

<div class="layer">
    <img src="${ require('../../assets/0.jpg') }" />
    <div> this is a <%= name %> layer </div>
    <% for (var i = 0; i < arr.length; i++) {  %>
        <%= arr[i] %>
    <% } %>
</div>

Using file-loader

{
    test: /\.(png|jpg|git|svg)$/i,
    loader: "file-loader",
    query: {
        name: 'assets/[name]-[hash:5].[ext]'
    }
}

Using url-loader

{
    test: /\.(png|jpg|git|svg)$/i,
    loader: "url-loader",
    query: {
        name: 'assets/[name]-[hash:5].[ext]',
        limit: 40000 // 40k, when the picture is less than 40k, it is packaged into base64
    }
}

Compressing Pictures Using image-webpack-loader

{
    test: /\.(png|jpg|git|svg)$/i,
    loaders: [
        "url-loader?limit=10000&name=assets/[name]-[hash:5].[ext]",
        "image-webpack-loader"  // Compressed pictures
    ]
}

Topics: Webpack less sass git