preface

In essence, Webpack is a static Module bundler for modern JavaScript applications. When WebPack works with an application, it recursively builds a Dependency graph containing every module the application needs, and then packages all of those modules into one or more bundles.

Starting with WebPack V4.0.0, you don’t have to import a configuration file. However, WebPack is still highly configurable. There are four core concepts you need to understand before you begin:

  • The entrance (entry)
  • Output (output)
  • loader
  • The plug-in (plugins)

This document is intended to give an introduction to the use of WebPack.

Create a new project webPack1.0.0 and initialize package.json

Type the command

mkdir webpack1.0.0// Create the webpack1 project.0.0
cd ./webpack1.0.0// Go to project path NPM init // initialize package.json fileCopy the code

2. Webpack webpack-cli webpack-dev-server plug-in is installed to provide corresponding installation packages for Webpack project.

Enter the command:

npm install webpack webpack-cli webpack-dev-server
Copy the code

After the command is completed, we will find a new node_modules folder in the project. This folder is used to store the dependencies installed in the project. It is not necessary to draw too much attention.

Iii. Complete project catalog and project files

3.1 Create three folders for the project (config — configuration folder dist — build folder SRC — project body folder)

Enter the command:

mkdir config dist src
Copy the code

As shown, three folders have been added:

3.2. Create HTML and JS files for project entry

Enter the command:

Touch dist/index.html SRC /index.js // This command is not supported by Windows. You need to manually create this commandCopy the code

4. Execute webpack command.

4.1 Configure the build command in package.json -> scripts. The configuration is shown

After the configuration, run the following command:

npm run  build
Copy the code

After executing the command, you will find that there is main.js in the dist folder. When the command is run, NPM takes out the command corresponding to build and executes it in the Node environment. The default entry for webpack is SRC /index.js, and the default packaging mode is –model development. There are two packaging modes in total:

  • — Model Development
  • — Model Production

The command configuration of the generation environment is shown as follows:

After the configuration, run the following command:

npm run  build:prod
Copy the code

After the command is executed, the result is the same as the preceding one. The yellow warning message disappears, and the packed file is smaller.

After the above operation is completed, the preliminary packaging process of Webpack will have some understanding, but how can webpack be so simple to use in real projects, next we will talk about the focus of Webpack, from the above results we are not difficult to find that Webpack has the function of encoding packaging and compiling, But to use it freely in large projects we need to master webpack configuration file writing, the following one to introduce the specific content of webpack configuration file.

5. Webpack configuration file structure introduction

5.1 WebPack Configuration File Introduction and Enablement

Starting with WebPack V4.0.0, you don’t have to import a configuration file. However, WebPack is still highly configurable. There are four core concepts you need to understand before you begin:

  • —— (Entry) Indicates the entry for packaging files (SRC /index.js is the default entry). Multiple entries are supported
  • Output —— (output) Output position of the compressed file
  • The loader —- (loader) escapes corresponding files and parses them into files recognized by the browser
  • —— (plugins) plugins are designed to solve other things that loader cannot implement.

With the concept behind us, let’s create a webpack.dev.js and do a simple configuration parsing.

Touch config/webpack.dev.js // This command is not supported by the Windows operating systemCopy the code

Configuration file class capacity, and configuration introduction

const HtmlWebpackPlugin = require('html-webpack-plugin'); // Install via NPM
const path = require('path');        // Node has the built-in path module, which integrates the file system path operation API

const config = {
    mode: 'development'.// The webpack mode, described in the command above, can also be configured in this configuration
    entry: {    //js entry file, support multi-entry comment ①
        main: path.resolve(__dirname,'.. /src/index.js')},output: {   // Js package compressed export file, multi-entry corresponding configuration should make relative changes note ②
        path: path.resolve(__dirname,'.. /dist'),
        filename:'bundle.js'
    },
    module: {
        rules: [] // Configure loder rules, scope, control output name, location, etc. The main function is to compile and parse files; Do not use loader temporarily
    },
    plugins: [
        new HtmlWebpackPlugin({template: './src/index.html'})  // Provide HTML template according to the project, generate a new page, and the corresponding output package compressed output JS, link to the page; For details, see Note 4]};module.exports = config;
Copy the code

Here is a link guide to code annotation in detail (it is recommended to go into more detail after this article is complete) :

Packing entry details – note ①

Package output details – comments ②

HTML template plugin – comment ④

Next, we will adjust the contents of the projects completed in section 1 ~ 3 above. We will empty the files in Dist and add index.html template HTML to the SRC folder. The file directory after completion is shown in the figure:

Next, we installed the uninstalled packages used in the project using NPM install html-webpack-plugin. The rest of the action is to reconfigure the commands for the webpack package. In section 3, we describe how to configure the command to run in package.json. Here we post the package.json code:

{
  "name": "Webpack - 1.0"."version": "1.0.0"."description": "Webpacke Basic Training"."author": "Zhang Xiao"."license": "ISC"."main": "index.js"."scripts": {  // NPM run command configuration
    "build": "webpack --config config/webpack.dev.js"  // Configuration of the package command --config indicates which file configuration is used to start the project package
  },
  "dependencies": {   // Third-party installation packages required by the project
    "webpack": "^ 4.29.6"."webpack-cli": "^ 3.2.3"."webpack-dev-server": "^ 3.2.1." "}}Copy the code

Command line run the following command:

npm run build
Copy the code

The result after running is as shown in the figure:

5.2 Webpack-dev-server Startup service and command parameters

The purpose of webpack-dev-server is to package the project and start a service that can be viewed directly from the project page in the browser. The specific configuration is as follows: webpack.dev.js add devServer and modify:

const HtmlWebpackPlugin = require('html-webpack-plugin'); // Install via NPM
const path = require('path');        // Node has the built-in path module, which integrates the file system path operation API

const config = {
    mode: 'development'.// The webpack mode, described in the command above, can also be configured in this configuration
    entry: {    //js entry file, support multi-entry comment ①
        main: path.resolve(__dirname,'.. /src/index.js')},output: {   // Js package compressed export file, multi-entry corresponding configuration should make relative changes note ②
        path: path.resolve(__dirname,'.. /dist'),
        filename:'bundle.js'
    },
    module: {
        rules: [] // Configure loder rules, scope, control output name, location, etc. The main function is to compile and parse files; Do not use loader temporarily
    },
    plugins: [
        new HtmlWebpackPlugin({template: './src/index.html'})  // Provide HTML template according to the project, generate a new page, and the corresponding output package compressed output JS, link to the page; For details, see Note 4].devServer: {        //webpack-dev-server configuration (development environment only)
		contentBase: path.join(__dirname, './dist'), // Where to compile the package file
		publicPath: '/'.port: 8080.// Server port number
		host: '0.0.0.0'.proxy: {},                  // List of agents
		compress: true.historyApiFallback: true.// Enable server history redirection mode}};module.exports = config;
Copy the code

Json file to add the development startup command as follows:

{
  "name": "Webpack - 1.0"."version": "1.0.0"."description": "Webpacke Basic Training"."main": "index.js"."scripts": {
    "build": "webpack --config config/webpack.dev.js"."dev" : "webpack-dev-server --config config/webpack.dev.js --color --progress --hot" // --color enable color printing --progerss enable process monitoring --hot enable hot loading
  },
  "author": "Zhang Xiao"."license": "ISC"."dependencies": {
    "babel-loader": "^ 8.0.5"."html-webpack-plugin": "^ 3.2.0"."webpack": "^ 4.29.6"."webpack-cli": "^ 3.2.3"."webpack-dev-server": "^ 3.2.1." "}}Copy the code

Add the webpack-dev-server command to the webpack-dev-server command.

npm run dev
Copy the code

Open the page http://localhost:8080/ to view the result as shown in the figure

The above is a simple webpack application of the whole process of the example, I recommend some webpack commonly used some loader, plugins use.

Vi. Loader is commonly used in Webpack project and its configuration.

6.1 Loader used for JavaScript

  • “Babel-core” //JavaScript compiler core babel-core (required)
  • “Babel-loader” //JavaScript compiler babel-loader (mandatory)
  • “Babel-plugin-transform-runtime” //JavaScript runtime environment converter
  • “Babel-preset -stage-0” //ES6,ES7 grammar conversion ES5 compiler (ES7 proposal and includes stage-2, stag-1)
  • “Babel-polyfill” //IE lower version extension JS some apis (such as Promise Object.defindProperty) (install IE lower version compatibility based on project requirements)
  • “Babel-runtime” // provides the ability to convert ES6 to an ES5 runtime environment without polluting the global completion code population
  • “Babel-plugin-transform-decorators-legacy” //JavaScript decorator syntax compiler (added to use @ syntax)
  • “Babel-plugin-transform-react-jsx” //react JSX syntax converter
  • “Babel-plugin-react-html-attrs” // the react DOM attribute recognizes the syntax converter
  • “Babel-pretzel-react” // React syntax compiler (pretzel-loader) // Pretzel-loader (pretzel-loader) Tells babel-loader how to process the corresponding syntax file when it is used. The configuration file name is.babelrc; Babelrc is configured as follows:
{
    "presets": [
        "env"."react"."stage-0"]."plugins": [
        "transform-decorators-legacy"."transform-react-jsx"["transform-runtime",
            {
                "helpers": false."polyfill": false."regenerator": true."moduleName": "babel-runtime"}]."react-html-attrs"]}Copy the code

Add loader rules to webpack.dev.js -> module.rules; Add the following configuration:

module: {
    rules: [{
      test: /\.js$/.loader: "babel-loader".options: {
        cacheDirectory: false.babelrc: true
      },
      exclude: path.resolve(__dirname, 'node_modules/'),}}]Copy the code

Babelrc configuration details can be found on the official website

6.2 Loader used by the CSS

  • “Style-loader” // style loader (mandatory)
  • “Css-loader” // CSS-loader (mandatory)
  • “Autoprefixer” // CSS3 automatic completion function
  • “Postcss-cssnext” // Take advantage of some additional CSS specifications added by CssNext,
  • “postcss-loader”
  • “Less “: // The following are all loaded libraries using less syntax
  • “less-loader”
  • “Node-sass “: “^4.5.3”, // all the following are loaded libraries using sass, SCSS syntax
  • “Sass – loader”, “^ 6.0.6”,

Postcss-loader also needs to be configured to tell the loader how to compile CSS. The configuration file postcss.config.js is as follows:

module.exports = {
    plugins: {
        'postcss-cssnext': {},}};Copy the code

For details about postCSS configuration, see the official website

Add loader rules to webpack.dev.js -> module.rules; Add the following configuration:

module: {
    rules: [{
			test: /\.css$/.use: [{
					loader: 'style-loader'.options: { sourceMap: false}}, {loader: 'css-loader'.options: { sourceMap: false}},'postcss-loader',]}, {test: /\.less$/.use: [{loader: 'style-loader'.options: {sourceMap: false}},
        {loader: 'css-loader'.options: {sourceMap: false}},
        {loader: 'postcss-loader'.options: {sourceMap: false}},
        {loader: 'less-loader'.options: {sourceMap: false}}}, {test: /\.(scss|sass)$/.use: [{loader: 'style-loader'.options: {sourceMap: false}},
        {loader: 'css-loader'.options: {sourceMap: false}},
        {loader: 'postcss-loader'.options: {sourceMap: false}},
        {loader: 'sass-loader'.options: {sourceMap: false}}}}]]Copy the code

6.3 Loader used to load resource files

  • “File-loader” File processing loader
  • “Url-loader” URL link processes the loader

Add loader rules to webpack.dev.js -> module.rules; Add the following configuration:

module: {
    rules: [{
      test: /\.(png|jpg|gif|ico|jpeg|bmp|swf)$/.exclude: path.resolve(__dirname, 'node_modules/'),
      use: [{
        loader: 'url-loader'.options: {
          limit: 10000,
          name(file) { // Image processing exceeds 10000 Kb
            return file.replace(/.*assets(\/|\\)/.' ').replace(/\\/g.'/'}}}]}, {test: /\.(woff|woff2|svg|eot|ttf|otf)$/.exclude: path.resolve(__dirname, 'node_modules/'),
      use: [{
        loader: 'file-loader'.options: {
          limit: 10000.name: 'fonts/[name].[ext]'}}}}]]Copy the code

There are many types and uses of Webpack loaders. Here are several commonly used loaders. Interested students can go to the official website to check

Plugins are commonly used in Webpack projects and their configuration.

7.1 Common Plug-ins

  • The HtmlWebpackPlugin template generates HTML and links the entry JS plug-in
  • Inline-manifest-webpack-plugin Manifest cache configuration plug-in
  • Copy-webpack-plugin copies the plugin file
  • The Dotenv – Webpack environment variable loads the plug-in
  • Webpack-parallel-ugli-fi -plugin js compression plugin
  • Optimize – CSS -assets-webpack-plugin CSS extract plugin
  • Mini-css-extract-plugin CSS compression plugin

Add plugin usage rules in the webpack.dev.js -> plugins option; Add the following individual plug-in configurations:

plugins: [
	new webpack.DefinePlugin({  // Environment variable assembly
		'process.env': {
			NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'development'),
			NODE_APIENV: JSON.stringify(process.env.NODE_APIENV || 'development'),
			WITH_TRACKER:process.env.WITH_TRACKER
		},
	}),
	new CopyWebpackPlugin([{    // Copy the file
		from: path.resolve(__dirname, '.. /static'),
		to: path.posix.join('static'),
		ignore: ['*'] {},from: path.resolve(__dirname, '.. /app/assets/javascripts'),
		to: path.posix.join('javascripts'),
		ignore: ['*']}]),]Copy the code

Here is not an introduction to the use of each plug-in rules and configuration parameters, you can read according to the plug-in official website