Get you started with Webpack and what can it do?

Preface

Original intention: In this article, we will talk about Webpack, what it can do and why we should use it. Share the notes I have compiled with you. If you have any mistakes, please point out. If you don’t like it, don’t spray.

Suitable for the crowd: the front-end primary development, the big guys detour.

This article explains Webpack 4.x, pay attention to the version.

Why use Webpack

Before we are the traditional way to develop a system, html, , css, jsthat's all. After the development is completed, it is directly deployed to the back-end personnel, of course, there is no problem. When our project requirements continue to increase, the more code becomes, the more difficult it is to maintain. There are hundreds or even thousands of lines of code in a file, and the code inside is even duplicated. You also need to worry about the scriptlabel dependency order and the code. The problem of variable pollution is modularized at this time to prevent variable pollution and dependency order problems. Now the mainstream packaging tool is Webpackstrong community support and support Es Module, CommonJsand AMDstandardization.

What is Webpack

WebpackModule is a packaged tool, you can Es Module, CommonJsgrammar process into code that can run a browser, the dependent files associated packaged into a jsfile.

What can Webpack do

Conducive to our convenient development, help us build a service locally, hot update of code changes and no page refresh, global injection of dependent files, code segmentation, code extraction, removal of unnecessary code, differentiation of environment variables, image optimization, etc., a strong community Plug-in extensions help us develop projects conveniently.

installation

The installation Webpackenvironment is also very simple. Generally, local installation is recommended. Global installation may conflict with other projects. Try to install locally.

cnpm i webpack@4 webpack-cli --save

The webpackgrammar installed above is webpack-clithe execution command of the command line operation

After the installation is complete, you can't directly webpack -vreport an error like this, because it will find your webpackenvironment globally , but you are installing locally, and using npx webpack -vthis will perform a local search in your project.

Get started quickly

Initialize the package.json file

Execute this command under your project file, and fill in the corresponding (Enter all the way), foolish operation.

npm init

Project structure

|- /node_modules
|- /src
   |- index.js
   |- news.js
   |- index.css
|- index.html
|- webpack.config.js
|- package.json

Entry

Entry packaging entry files, there are several forms of packaging entry, let's introduce them one by one.

Single entry

module.exports = {
    
    
    entry: "./src/index.js"
}

Multi-entry

Multi-entry packaging, the jsfile name is the key value of the object.

module.exports = {
    
    
    entry: {
    
    
        index: "./src/index.js",
        news: "./src/news.js"
    }
}

Array entry

Array packaging, entryreceiving an array object, only the last value of the parameter inside is the real packaging path, other parameters are to import the path file into the last parameter

module.exports = {
    
    
    entry: ["./src/news.js", "./src/index.js"]
}

// 上面entry那种操作,等同于如下:
// index.js
require("news.js")

In the above example, except for the last parameter, all other array parameters are imported into the last parameter file

Output

outputIf there is an entry file, there must be an export file,

module.exports = {
    
    
    output: {
    
    
        path: __dirname + "/dist",
        filname: "app.js"
    }
}

filenameThere are several name options, let me introduce them

  • [name] Use the name of the entry file
  • [chunkhash] The hash value is generated, which is parsed by the current file depends on, and a chunk is generated at the end, and the hash value is generated
  • [contenthash] When the content of the file changes, the hash value will change
  • [id] Use chunk id to generate file name
  • [hash] Use hash as the file name, each time the generated hash is different
module.exports = {
    
    
    output: {
    
    
        path: __dirname + "/dist",
        filname: "[name][id][contenthash].js"
    }
}

Loader

loaderWhat is it? We only talked about the jsrelevant ones above. WebpackBy default, we only recognize js files. Then Webpackhow to package jsthings jsother than packaging will report an error. What should I do? At this time loader, it loaderis a converter. Let ’s follow Take the cssfile as an example to explain

  • test receives a regular expression, matches the file suffix name, and successfully enters the loader for execution
  • use receives an array, when only one loader can be written as a string

css-loader

installation

npm i css-loader --save-dev

use

module.exports = {
    
    
     module: {
    
    
        rules: [
            {
    
    
                test: /\.css$/,
                use: ["css-loader"] or "css-loader"
            }
        ]
    }
}

After the configuration, loaderno error will be reported, but the code still does not take effect. It just parsed the cssfile, but didn't stylemount it on the page, it needs to be combined style-loader.

style-loader

installation

npm i style-loader --save-dev

use

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

In the above example, the loader must be executed sequentially, and the loader is executed from back to front. First, the css file is parsed, and then the parsed css file is mounted on the page style tag. At this time, the code will take effect.

Plugins

clean-webpack-plugin

At this time, if we modify the filename in the output and package it again, we can see that the old code in the previous dist package still exists. At this time, we want to generate a new dist directory every time we package, and then we need to use it To the plug-in.

Install the clean-webpack-pluginplug-in, my local installation is version 3.0.0

npm i clean-wenpack-plugin --save-dev

use

const {
    
     CleanWebpackPlugin } = require('clean-webpack-plugin')

module.exports = {
    
    
    plugins: [
        new CleanWebpackPlugin()
    ]
}

html-webpack-plugin

If distthere is no index.htmlfile in the directory after we have packaged it, then we can use the plug-in, and a htmlfile will be generated every time we package it , let’s install it below

The installation html-webpack-pluginI use here is version 3.2.0. It should be noted that the nodehigher your local version, the newer the plug-in installed, and the new version may be webpack4a bit incompatible with or even cause code errors.

npm i html-webpack-plugin@3.2.0 --save-dev

use

const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    
    
    plugins: [
        new HtmlWebpackPlugin({
    
    
            template: './index.html',  // 以咱们本地的index.html文件为基础模板
            filename: "index.html",  // 输出到dist目录下的文件名称
        }),
    ]
}

html-webpack-pluginReceiving a plug-in object that has some property values, not one by one example where we can see the article "html-webpack-plugin uses the whole solution" .

Complete code

const {
    
     CleanWebpackPlugin } = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    
    
    entry: "./src/index.js",
    output: {
    
    
        path: __dirname + "/dist",
        filename: "index.js"
    },
    module: {
    
    
        rules: [
            {
    
    
                test: /\.css$/,
                use: [
                    "style-loader",
                    "css-loader"
                ]
            }
        ]
    },
    plugins: [
        new CleanWebpackPlugin(),
        new HtmlWebpackPlugin({
    
    
            template: './index.html',
            filename: "index.html",
        }),
    ]
}

to sum up

At this point, our webpackintroduction is finished, and a simple packaging is implemented. webpackBy default, only jsfiles are recognized . If you want to use cssand pictures, you can use loaderto convert. We can see the final package complete, distthe directory or some of the original file html, , css, jsdirectly distcontracted background deployed on the line.

For more frequently used ones to share in loaderthe pluginnext issue, remember to follow me ❤❤❤.

thank

Thank you for reading this article. I hope it will be helpful to you. If you have any questions, please correct me.

I’m a frogman (✿◡‿◡), if you think it’s ok, please like it ❤.

Interested friends can join [Front-end entertainment circle exchange group] Welcome everyone to communicate and discuss

Writing is not easy, "Like" + "Watching" + "Repost" Thank you for your support❤

Good articles in the past

"Talk about using Decorator in Vue projects"

"Talk about what are CommonJs and Es Module and their difference"

"Map that takes you easily to understand the data structure"

"Do you know all the JavaScript tips used in these jobs?"

"[Recommended Collection] Share some commonly used Git commands in work and how to solve special problem scenarios"

"Do you really understand the features of ES6?

Guess you like

Origin blog.csdn.net/weixin_44165167/article/details/114917010