Webpack definition

Webpack is a front-end resource builder, a static Module bundler. In webpack’s view, all the front-end resource files (JS /json/ CSS /img/less/…) Will be treated as modules. It will carry out static analysis according to module dependencies and generate corresponding static resources (bundles).

Webpack has five core concepts

1.Entry

The Entry indicates which file webPack starts packing as the Entry point to analyze and build the internal dependency graph/tree.

In layman’s terms, it tells WebPack which file of the project to start with to package the entire project.

2.Output

Output indicates where the resource bundles Output from WebPack go and how to name them.

3.Loader

Loader allows Webpack to handle non-javascript text (Webpack only handles JavaScript itself, so Loader can be interpreted as an extension of WebPack, Different file processing requires different loaders.

(Can be understood as a translator, different languages need different translators)

4.Plugins

Plugins can be used to perform a much wider range of tasks. Plug-ins range from packaging optimization and compression to redefining variables in the environment.

5.Mode

Mode instructs Webpack to use the configuration of the corresponding Mode.

Development mode and production mode:

The title describe The characteristics of
development The value of process.env.node_env in DefinePlugin is set to development. Enable NamedChunksPlugin and NamedModulesPlugin. An environment in which code debugging can run locally
production The value of process.env.node_env in DefinePlugin is set to production. Enable FlagDependencyUsagePlugin FlagIncludedChunksPlugin, ModuleConcatenationPlugin NoEmitOnErrorsPlugin, OccurrenceOrderPlugin, SideEffectsFlagPlugin and TerserPlugin. An environment that optimizes code to run online

Webpack eyes

Create a new folder and open it in vscode

Initialize the pakage.json file

The terminal type NPM init, give it a name and leave the default press enter to generate package.json.

Install required third-party packages

Install Webpack and WebPack-CLI globally

NPM I [email protected] webpack-cli -g

Webpack is running in the Node environment, we need to install the following two NPM packages:

NPM I [email protected] webpack-cli -d

-d is short for –save-dev means add to development dependency, everything in Webpack is a development dependency. Once installed, the node_moudel dependency package appears and you can write code.

Write a program

Create a SRC folder and a build folder

The SRC folder is used to hold the code we wrote, and the Build folder is used to hold the webPack wrapped files.

Webpack uses tests

Create a new index.js file under SRC and write a simple js code:

function add(x, y) {
    return x+y
}

console.log(add(1.2));
Copy the code

In terminal: webpack. / SRC /index.js -o./build/ build.js –mode=development

This command means:

/ SRC /index.js and output it to./build/ build.js; The overall packaging environment is the development environment.

For Webpack5, run the following command:

webpack --entry ./src/index.js -o ./build/built.js --mode=development )

You can see that there is a main.js file under build/built. — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — – in the terminal: webpack ./src/index.js -o ./build/built.js –mode=production

This command means:

/ SRC /index.js and output it to./build/ build.js; The overall packaging environment is the production environment. If you look at main.js this time, you can see that code is compressed in production.

Run the code

1. Node environment running:

node ./build/built.js/main.js

2. Create an HTML page. SRC import the built-in /main.js file and view the result on the browser console.

Conclusion:

1. Webpack can handle JS/JSON resources, not CSS/IMG and other resources 2. Production and development environments compile ES6 modularity into modularity 3 that browsers recognize. The production environment has one more compressed JS code than the development environmentCopy the code

Webpack packs style resources

Create a new folder and open it up in vscode,

Since webpack cannot package style resources,loader needs to use the configuration file. Create a configuration file that is the same as the SRC folder: webpack.config.js

Webpack configuration file

Function: tells webpack what to do, when running webpack will load the instructions inside

Configuration contents:

const { resolve } = require('path')
module.exports = {
    / / webpack configuration

    // The entry point
    entry: './src/index.js'./ / output
    output: {
        // Output the file name
        filename: 'built.js'.// Output path
        // The __dirname node.js variable, which represents the absolute path to the current file root directory
        // resolve path stitching
        path: resolve(__dirname, 'build')},// Loader configuration
    module: {
        rules: [
            // Loader configuration details
            {
              // Which files to match
              test: /\.css$/.// Which loaders are used for processing
              use: [
                  // The sequence of loader execution in the use array is from right to left and from bottom to top
                  // Create a style tag, insert the js style resource, add it to the head to take effect
                  'style-loader'.// Load the CSS file into the common.js module, which contains the style string
                  'css-loader']]}},// Plugins are configured
    plugins: [
        // Detailed plugins configuration]./ / mode
    mode: 'development' // Optional values: development, production
}
Copy the code

In the terminal:

npm init

npm i webpack webpack.cli -D

npm i css-loader style-loader
Copy the code

Run:

webpack

Create a new index.html and run the test in your browser:

packaging

webpack

Parsing less files

/* webpack.config.js: All build tools (webpack being one of them) run on Node.js, and the modularity default is common.js */
const { resolve } = require('path')
module.exports = {
    / / webpack configuration

    // The entry point
    entry: './src/index.js'./ / output
    output: {
        // Output the file name
        filename: 'built.js'.// Output path
        // The __dirname node.js variable, which represents the absolute path to the current file root directory
        // resolve path stitching
        path: resolve(__dirname, 'build')},// Loader configuration
    module: {
        rules: [
            // Loader configuration details
            {
              // Which files to match
              test: /\.css$/.// Which loaders are used for processing
              use: [
                  // The sequence of loader execution in the use array is from right to left and from bottom to top
                  // Create a style tag, insert the js style resource, add it to the head to take effect
                  'style-loader'.// Load the CSS file into the common.js module, which contains the style string
                  'css-loader'] {},test: /\.less$/,
                use: [
                    'style-loader'.'css-loader'.// To convert less files into CSS files, you need to install [email protected]
                    'less-loader']]}},// Plugins are configured
    plugins: [
        // Detailed plugins configuration]./ / mode
    mode: 'development' // Optional values: development, production
}
Copy the code

Testing:

Webpack packs HTML resources – using plug-ins

/* loader: 1. Download the plugin. 2. Download 2. Import 3. Configure using */
// Introduce the htmL-webpack-plugin
const HtmlWebpackPlugin = require('html-webpack-plugin')
const {resolve} = require('path')

module.exports = {
    entry: './src/index.js'.output: {
        filename: 'built.js'.path: resolve(__dirname, 'build')},module: {
        rules: []},// Plugins are configured
    plugins: [
        // Detailed plugins configuration
        // the html-webpack-plugin creates an empty HTML file by default, automatically importing all the resources we want to pack
        new HtmlWebpackPlugin()

    ],
    / / mode
    mode: 'development' // Optional values: development, production
}
Copy the code

Webpack packs image resources

const {resolve} = require('path')
const HtmlWebpackLoader = require('html-webpack-plugin')
module.exports = {
    entry: './src/index.js'.output: {
        filename: 'built.js'.path: resolve(__dirname, 'build')},module: {
        rules: [{test: /\.less$/,
                use: [
                    'style-loader'.'css-loader'.'less-loader'] {},// Problem: img images in HTML cannot be processed by default
                // Loader to process image resources
                test: /\.(png|jpg|gif)$/.// Use the use array for multiple loaders, only one loader uses the loader attribute
                // url-loader depends on file-loader
                loader: 'url-loader'.options: {
                    // Images below XKB are base64
                    // Base64 advantage: reduces server stress
                    // Base64 disadvantages: It can make images bigger, so use base64 for small images
                    limit: 12*1024}}},plugins: [
        new HtmlWebpackLoader({
            template: './src/index.html'})].mode: 'development'
}
Copy the code

Webpack packs other resources

Other resources like font ICONS… I don’t need to do anything, just output it.

module: {
        rules: [{// Package other resources
                exclude: /\.(css|js|less|html|img)$/,
                loader: 'file-loader'}},Copy the code

Auto-build auto-pack in Webpack (webpack-dev-serve)

Configure in webpack.config.js:

Write underneath the five core modules of WebPack, plus a devServer object.

Webpack – Separate CSS from a packed CSS file

Prevent the packed JS file from being too large.