What is Webpack?

Webpack is essentially a static module packaging tool for modern JavaScript applications, according to the webPack website. When WebPack processes the application, it internally builds a dependency diagram (shown below) that maps to each module required for the project and generates one or more bundles.

We can summarize this briefly: Webpack is a tool for packaging modular Javascript. It will start from the entry module, identify the modular import statements in the code, recursively find all the dependencies of the entry and exit files, and package the entry and all its dependencies into a single file. It is the withdrawal of engineering, automation ideas in the front end development.

At the beginning of webpack experience

1. Install the Node environment

Webpack depends on the Node environment, so make sure that you have installed the Node environment before installing WebPack. It is recommended to install the latest version of Node to improve the packaging speed of WebPack.

2. Install webpack

Webpack can be installed locally or globally. Installing webPack globally will lock the webpack in your project to the specified version, causing different projects to rely on different versions of the conflict, build failure, so we will only introduce the way of partial installation.

  1. Initialize the NPM configuration file npm init -y
  2. Installing the core librarynpm install --save-dev webpack
  3. Install the command line toolnpm install --save-dev webpack-cli

3. Start the webpack

Let’s write some code to see how WebPack works.

  1. Create a SRC folder in the project and add index.js and hello.js in the SRC folder

hello.js

export function helloWebpack() {
   return 'hello Webpack'
}
Copy the code

index.js

import { helloWebpack } from './hello';
document.write(helloWebpack())
Copy the code
  1. Execute commands on the command line./node_modules/.bin/webpackAfter the command is executed, the following output is displayed:

Dist ()=>{“use strict”; dist ()=>{“use strict”; document.write(“hello Webpack”)})(); . Main.js is the code that Webpack packaged according to the entry and module dependencies of our code.

  1. Create a new index. HTML file in the dist folder and import main.js to see how it works

index.html

<! DOCTYPEhtml>
<html lang="en">

<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
   <title>hello wepack</title>
</head>

<body>
   <script src="./main.js"></script>
</body>

</html>
Copy the code

Open index.html in your browser and the browser viewport displays Hello Webpack

So far we have a webpack experience on the completion of the first. As stated on the website, WebPack works out of the box without any configuration files. Webpack assumes that the entry point for the project is SRC /index.js, and then outputs the result in dist/main.js. And turn on compression and optimization in production.

Webpack base configuration structure

In the initial webPack experience above, we experienced the joy of WebPack out of the box, but often our projects need to continue to expand the power of WebPack to meet the needs of the customized project. Webpack also provides us with a default configuration file. We can create a webpack.config.js file in the project root directory, and webPack will use it automatically when we execute the webpack command.

The webpack.config.js configuration infrastructure is as follows:

module.exports = {
    entry: "./src/index.js".// Package the entry file
    output: "./dist".// Output directory
    mode: "production".// Package the environment
    module: {
        rules: [
        // Loader module processing]},plugins: [] // Plug-in configuration
};
Copy the code
  1. Entry: Specifies the webpack entry file

The first step in the Webpack implementation of the build will start with entry, which can be abstracted as input

// single entry SPA, essentially a string
entry:{
    main: './src/index.js'} == equivalent to shorthand === entry:"./src/index.js"

// Multi-entry is an object
entry:{
    index:"./src/index.js",
    login:"./src/login.js" 
}
Copy the code

2. Output: Package the transformed file and output it to the disk location. After a series of processing by Webpack, the final desired code is output.

 
output: {
    filename: "bundle.js".// The output file name
    path: path.resolve(__dirname, "dist")// Output file to disk directory, must be an absolute path
},

// Multi-entry processing
output: {
    filename: "[name][chunkhash:8].js".// Use placeholders and do not repeat file names
    path: path.resolve(__dirname, "dist")// Output file to disk directory, must be an absolute path
},
Copy the code

3. Mode: Specifies that the current build environment has three options: production, development, and None. The default is production. Setting mode automatically triggers webpack built-in functions for optimization.

 
mode: 'development'

// Can also be passed from CLI parameters
webpack --mode=development
Copy the code
options describe
development The value of process.env.node_env in DefinePlugin is set to development. Enable valid names for modules and chunks.
production The value of process.env.node_env in DefinePlugin is set to production. For the module and the chunk enable deterministic confusing name, FlagDependencyUsagePlugin, FlagIncludedChunksPlugin, ModuleConcatenationPlugin, NoEmitOnErrorsPlugin and TerserPlugin.
none No tuning options are used by default
  1. Loader: Module parser, or module parser.

Used to convert the original content of the module to new content as required. Webpack only knows how to handle JS and JSON modules by default, so it’s up to loader to handle other formats. A loader does only one thing

Common Loaders are as follows:

style-loader  // The content generated by csS-loader will be mounted to the heade section of the page in style
css-loader  // Analyze the relationship between CSS modules and synthesize a CSS
less-loader  // Convert less to CSS
sass-loader  // Convert Sass to CSS
ts-loader  // convert Ts to js
babel-loader  // Convert ES6, 7 and other new JS feature syntax
file-loader  // Process the image subgraph
eslint-loader  //eslint.Copy the code
  1. Module: Module, in Webpack everything is a module, a module corresponds to a file. Webpack recursively finds all dependent modules from the configured Entry. When webpack processes an unknown module, it is necessary to configure the module in Webpack. When the module is detected, what loader is used to process it.
 
module:{
  rules:[
    {
        test:/\.xxx$/,  // Specify a matching rule
        use:{
            loader: 'xxx-load' // Specify the loader to use}}}]Copy the code

Plugins: Extensions to WebPack

  • Plugins are used throughout the Webpack packaging process
  • The packaging process for WebPack has (lifecycle concept) hooks.

Plugins can do things for you when WebPack is running at a certain stage, similar to life cycle concept extensions that inject extension logic at certain points in the WebPack build process to change the build result or do what you want. Apply to the entire build process.

conclusion

The webPack installation and basic configuration was introduced in the first installment of the WebPack series, “Building WebPack From Scratch.” In the next section, we’ll learn more about WebPack by putting these configurations into practice.

Webpack: github.com/wanganni101… Switch to the corresponding branch.