Recently have leisure, to the lu side webpack document, will webpack usage and function of basic on the context, although each big the front frame of ecological system is more and more perfect, every basic framework with a set of standard scaffolding tools, but that is a good meal collocation, although also ok to use, or always feel where is not the matter, Just like driving a car in automatic mode, can not be according to their own project arbitrary collocation of functions. So today we’re going to take a good look at WebPack and see why.

The core concept

The core function of Webpack is modular packaging. Since it is packaging, it must involve entry and output, and the remaining two core concepts are loader, plugin and mode.

entry && output

Entry and output are literally entry and exit points for reading code during packaging and compiling output files.

mode

Mode is somewhat similar to semi-automatic mode: provide the mode configuration option and WebPack will automatically optimize it using the built-in functionality of the corresponding mode. This one sentence sums up the pattern. As for what features webPack will enable in which mode, see the following table:

options describe
development The value of process.env.node_env is set to development. Enable NamedChunksPlugin and NamedModulesPlugin.
production The value of process.env.node_env is set to production. Enable FlagDependencyUsagePlugin FlagIncludedChunksPlugin, ModuleConcatenationPlugin NoEmitOnErrorsPlugin, OccurrenceOrderPlugin SideEffectsFlagPlugin and UglifyJsPlugin.

loader

Loader is a loader used to convert the source code of a module. Loader can convert all types of files into valid modules that WebPack can handle, and then you can take advantage of WebPack’s packaging capabilities to process them.

Loader has two goals in the webpack configuration:

  1. The test property identifies the files or files that should be converted by the corresponding loader.
  2. The use attribute indicates which loader should be used for conversion.
const config = {
  module: {
    rules: [
      { test: /\.txt$/, use: 'raw-loader'}]}};Copy the code

In the above configuration, the rules property is defined for a single Module object, which contains two required properties: test and use. This tells the Webpack compiler the following:

“Hey Webpack compiler, when you encounter a” path that is resolved to ‘.txt’ in require()/import statement “, use raw-loader to convert it before you package it.

You can go to the Loader list and select an appropriate loader when you need to convert each file into a valid module that WebPack can handle

plugin

Plug-ins can be used to perform a wider range of tasks. Plug-ins range from packaging optimization and compression to redefining variables in the environment. Plug-in interfaces are extremely powerful and can be used to handle a wide variety of tasks. To use a plugin, you simply require() it and add it to the plugins array. Most plug-ins can be customized with options. You can also use the same plug-in multiple times for different purposes in a configuration file by using the new operator to create an instance of it. When you want to optimize something for something you can go to the plugins list and there are no plugins out of the box,

Here is an example of loader and plugin usage

const HtmlWebpackPlugin = require('html-webpack-plugin'); // Install const webpack = require('webpack'); // To access the built-in plugin const config = {... plugins: [ new HtmlWebpackPlugin({template:'./src/index.html'}})]; module.exports = config;Copy the code

HtmlWebpackPlugin is introduced to automatically generate an HTML file.

The configuration file

Although WebPack supports manually hitting webpack-CLI on the command line to build files, common projects are more complex, so WebPack supports providing configuration files. This is much more efficient than manually typing a large number of commands ina terminal. So let’s create a configuration file instead of using the CLI option:

const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')}};Copy the code

This is the simplest configuration file that defines input files and output files. Read and run SRC’s index.js file to output the generated bundle.js file to dist. Once you have such a configuration file, there are two ways to start it

  1. Run through the command line toolnpx webpack --config webpack.config.jsThis command runs the webpack command with the specified Webpack configuration file

If webpack.config.js exists, the webpack command will choose to use it by default. We use the –config option here just to show you that configuration files with any name can be passed. This is useful for complex configurations that need to be split into multiple files.

  1. NPM Scripts Considering that it is not particularly convenient to run the local Webpack using the CLI, we can set up a shortcut. Add an NPM script to package.json:
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"."build": "webpack"
},
Copy the code

Now, we can use the NPM run build command instead of the NPX command we used earlier.

To talk about my own understanding of Webpack, webpack is to weave a beautiful pearl necklace, then the configuration file is the chain of the necklace, and the loader list and plug-in list in Webpack are like raw materials, we can pick out the pearls we need from the raw materials. Entry and Output are the entrances and exits to select and polish the necklace. Now that we’re all set, we’re going to learn how to make a beautiful pearl necklace. The first is to learn how to polish the perfect entrance and exit. Then we have to learn what kind of beads to put where and how to put them.

Example – Create a React application from zero

Now we can complete a 0 to 1 configuration file for React step by step from simple to complex:

The implementation process

1. Initialize the NPM project and generate package.json.

Add public/index.html.

3, install Babel, create. Babelrc and configure.

Install react, react-dom, and react-hot-loader.

5, install webpack, create webpack.config.js to configure.

6, add SRC /index.js, SRC/app. js, SRC/app.css.

7. Configure package.json and modify the startup command.

8. Start the project

Specific steps

1. Initialize the NPM project and generate package.json

Create a new project and CD it in.

$ mkdir webpack-demo
$ cd webpack-demo
Copy the code

Create a package.json file, and if you want to skip initialization problems, add -y to install with default options:

npm init -y
Copy the code

2. Add public/index.html.

mkdir public
cd public
touch index.html
Copy the code

index.html

<! -- sourced from https://raw.githubusercontent.com/reactjs/reactjs.org/master/static/html/single-file-example.html --> <! DOCTYPE html> <html> <head> <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>React Starter</title>
</head>

<body>
  <div id="root"></div>
  <noscript>
    You need to enable JavaScript to run this app.
  </noscript>
  <script src=".. /dist/bundle.js"></script>
</body>
</html>
Copy the code

The bundle.js introduced here will be used later.

3. Install Babel and create. Babelrc.

cd. / NPM install -d @babel/[email protected] @babel/[email protected] @babel/[email protected] @babel/[email protected] touch.babelrcCopy the code

.babelrc

{
  "presets": ["@babel/env"."@babel/preset-react"]}Copy the code

Install react, react-dom, and react-hot-loader

npm i react react-dom -S
npm i react-hot-loader -D

Copy the code

5. We need to install webpack and the required development dependency, create webpack.config.js for configuration

npm i webpack webpack-cli webpack-dev-server style-loader css-loader babel-loader --save-dev
touch webpack.config.js
Copy the code

webpack.config.js

const path = require("path");
const webpack = require("webpack");

module.exports = {
  entry: "./src/index.js",
  mode: "development",
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /(node_modules|bower_components)/,
        loader: "babel-loader",
        options: { presets: ["@babel/env"]}}, {test: /\.css$/,
        use: ["style-loader"."css-loader"]
      }
    ]
  },
  resolve: { extensions: ["*".".js".".jsx"] },
  output: {
    path: path.resolve(__dirname, "dist/"),
    publicPath: "/dist/",
    filename: "bundle.js"
  },
  devServer: {
    contentBase: path.join(__dirname, "public/"),
    port: 3000,
    publicPath: "http://localhost:3000/dist/",
    hotOnly: true
  },
  plugins: [new webpack.HotModuleReplacementPlugin()]
};
Copy the code

6. Add SRC /index.js, SRC/app. js, and SRC/app.css.

mkdir src
cd src
touch index.js
touch App.js
touch App.css
Copy the code

index.js

import React from "react";
import ReactDOM from "react-dom";
import App from "./App.js";
ReactDOM.render(<App />, document.getElementById("root"));
Copy the code

App.js

import React, { Component} from "react";
import {hot} from 'react-hot-loader';
import "./App.css";

class App extends Component{
  render() {return(
      <div className="App"> <h1> Hello</h1> </div> ); }}export default hot(module)(App);
Copy the code

App.css

.App {
  margin: 1rem;
  font-family: Arial, Helvetica, sans-serif;
  border: 1px solid red;
}
Copy the code

7. Configure package.json and modify the startup command.

Configure the scripts field in package.json.

"scripts": {
    "start": "webpack-dev-server --mode development"."test": "echo \"Error: no test specified\" && exit 1"
  }
Copy the code

8. Start the project.

npm start
Copy the code

Type http://localhost:3000 in your browser to launch the project

Making the address