Initialize the project

mkdir new-webpack-react
cd new-webpack-react
npm init
Copy the code

Install webpack

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

Note: Meaning of various abbreviations of NPM:

  • -i equals to install -s
  • -s is short for –save, and puts the package name and version number in Dependencies, which need to be published to production
  • -d is –save-dev, and the package name and version number are stored in devDependencies of package.json. The plug-in in devDependencies is only for development, not production

Configure the configuration of the webpack.config.js file

1. First of all, the configuration file of Webpack needs several configurations:

  • Configuration Entry
  • Configuration exit (Output)
  • Configure loaders for various resources
  • Plugins solve other things that loader cannot implement
  • The parser (resolve),
  • Inject the script of the packaged JS entry file into the HTML template using the HtmlWebpackPlugin
const path = require('path'),
  htmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  mode: 'development', /* Entry values are of three types: 1. String, 2. Array, 3. Object, array when multiple entry files, use the array method, such as relying on the third-party library bootstrap, the final bootstrap will be appended to the package index.js, the last of the array will beexportObject sets multiple packing targets. Each key-value pair corresponds to an entry file. Path. resolve(__dirname,'.. /src/index.js'Output: {filename:'[name].index.js'// Output file name, self set js path chunkFilename:'chunk/[name].[hash].js'Path: path.resolve(__dirname,'.. /dist'), // Output file location publicPath:' '// Static resource path prefix}, plugins: HTML */ new HtmlWebpackPlugin ({template: path.resolve(__dirname,'.. /template/index.html'// Set favicon's path // favicon:'./src/assets/favicon-32x32-next.png'}})]Copy the code

Packagejson file configuration commands and perform, you can see the dist folder or become main. 923 dea72093bed3467ee files

"scripts": {
    "start": "webpack --config build/webpack.config.js"
  // "start": "webpack"
  },
Copy the code

Note: if webpack.config.js exists in the root directory, the webpack command will use it by default.

You can also specify the configuration file using the webpack –config webpack.config.js command

  1. Configure some common Loaders, CSS, and JS

Install NPM install –save-dev style-loader CSs-loader less-loader sass-loader less file-loader

module: {
    rules: [
      {
        test: /\.scss$/,
        use: [
          'style-loader', // creates style nodes from JS strings
          'css-loader', // translates CSS into CommonJS
          'sass-loader' // compiles Sass to CSS, using Node Sass by default
        ]
      },
      {
        test: /\.less$/,
        use: [
          {loader: 'style-loader'},
          {loader: 'css-loader'},
          {loader: 'less-loader',
            options: { javascriptEnabled: true, modifyVars: themeVariables} // modifyVars global overlay style, for example: ANTD custom global overlay style}]}, {test: /\.css$/,
        use: [devMode ? 'style-loader' : MiniCssExtractPlugin.loader, 'css-loader'] {},test: /\.(eot|woff|woff2|ttf|svg|png|jpe? g|gif)(\? \S*)? $/, use: [ { loader:'file-loader',
            options: {
              // name: '[name].[ext]'// name can also be a function name(file) {if (devMode) {
                  return '[name].[hash].[ext]'
                }
                return '[name].[ext]'
              }
            },
            exclude: /node_modules/
          }
        ]
      }
    ]
  }
Copy the code

Compile javascript with Babel: cnpm install –save-dev babel-core babel-loader babel-plugin-import babel-plugin-transform-class-properties babel-plugin-transform-decorators-legacy babel-plugin-transform-runtime babel-polyfill babel-preset-env babel-preset-es2015 babel-preset-stage-0 babel-preset-stage-1

The react code is compiled to install babel-preth-react react-hot-loader

Create a new.babelrc file at the root

{
"presets": ["es2015"."react"."stage-1"]."plugins": [
  "transform-runtime"."transform-decorators-legacy"."transform-class-properties"."react-hot-loader/babel"["import",
    {
      "libraryName": "antd"."libraryDirectory": "es"."style": true}]] /* transform-runtime: transform-remove-console: * transform-decorators-legacy: decorator configuration @ * transform-class-properties: React-hot-loader: hot updates to plugins */Copy the code

Add js, JSX compiler to rules of webpack.config.js

{
  test: /\.(js|jsx)$/,
  exclude: /node_modules/,
  loader: 'babel-loader'
}
Copy the code

Next, do some plugins.

First, HtmlWebpackPlugin configuration optimization

HtmlWebpackPlugin each attribute configuration details:

Title: Generates the title of the HTML file

Filename: indicates the name of the output HTML file

Template: indicates the path of the HTML template file

Inject: Injection option. There are four options with values true, body, head, and false.

  • True: The default, script tag at the bottom of the body of the HTML file
  • Body: The script tag is at the bottom of the body of the HTML file (same as true)
  • Head: The script tag is inside the head tag
  • False: Generates an HTML file instead of inserting the generated JS file

Minify: To compress HTML files, the attribute value of minify is either a compression option or false. The default value is false and does not compress the generated HTML file.

New HtmlWebpackPlugin({// package output HTML title:'Hello World app', minify: {// compress HTML file removeComments:true// collapseWhitespace in HTMLtrue// Delete whitespace and newline characters minifyCSS:true// compress inline CSS}, filename:'index.html',
    template: path.resolve(__dirname, '.. /template/index.html')})Copy the code

Second, the clean – webpack – the plugin

CNPM install –save-dev clean-webpack-plugin plugin: CNPM install –save-dev clean-webpack-plugin

const CleanWebpackPlugin = require('clean-webpack-plugin')
plugins:[
    new CleanWebpackPlugin(['dist']]Copy the code

After version 3.0:

const { CleanWebpackPlugin } = require('clean-webpack-plugin'), plugins:[new CleanWebpackPlugin(), // Note: do not upload files that need to be clean]Copy the code

Happypack CNPM install happypack –save-dev

The reason: Webpack running on Node.js is a single-threaded model, so the things that Webpack needs to deal with need to be done one by one, not at the same time. We need Webpack to be able to handle multiple tasks at the same time, giving full play to the power of multi-core CPU computer. HappyPack allows Webpack to do this by splitting tasks into sub-processes for concurrent execution, which then send the results back to the main process.

And because JavaScript is a single-threaded model, the ability of multi-core CPU can only be realized through multi-process, but not through multi-thread.

HappyPack is not friendly to file-loader and URl-loader. Therefore, it is not recommended to use HappyPack.

Modify the webpack.config.js file:

const HappyPack = require('happypack');
const os = require('os'); <! Const happyThreadPool = happypack.threadpool ({size: os.cpus().length}); module.exports = { module: { rules: [ {test: /\.(js|jsx)$/,
        loader: 'happypack/loader? id=happyBabel'// Exclude: /node_modules/ / exclude: /node_modules/ // exclude: /node_modules/ /},}, plugins: [ new HappyPack({ id:'happyBabel'// Use the id to identify where the happypack class file loaders: [{loader:'babel-loader'}], threadPool: happyThreadPool, // share process pool verbose:true, // Allow HappyPack to print logs})]}Copy the code

4, progress-bar-webpack-plugin Compels the progress bar plugin

You can see the compile time progress on the command line

const ProgressBarPlugin = require(progress-bar-webpack-plugin)
new ProgressBarPlugin({
     format: ' build [:bar] ' + chalk.green.bold(':percent') + ' (:elapsed seconds)'
   }),
Copy the code

NPM install –save-dev mini-css-extract-plugin NPM install –save-dev mini-css-extract-plugin

A plug-in that extracts CSS as a separate file, creates a CSS file for every JS file that contains CSS, and supports on-demand loading of CSS and sourceMap

  • Asynchronous loading
  • Better performance without recompiling
  • Only for CSS
const MiniCssExtractPlugin = require('mini-css-extract-plugin')


 {
        test: /\.css$/,
        use: [devMode ? 'style-loader' : MiniCssExtractPlugin.loader, 'css-loader']
},
      
new MiniCssExtractPlugin({
      filename: devMode ? '[name].[hash:4].css' : '[name].[contenthash].css',
      chunkFilename: devMode ? '[id].[hash:4].css' : '[id].[contenthash].css',})Copy the code

Six, webpack DefinePlugin

Create a global variable that can be configured at compile time to distinguish between development, test, and production environments at compile time.

Because the environment variable process.env.node_env in nodejs is available only in the Node environment, while the variables provided by webpack.defineplugin are available in the browser environment

 new webpack.DefinePlugin({
  'gropuPcApiType': {
    ENV: JSON.stringify(process.env.ENV)
  }
})

index.js:
console.log('gropuPcApiType', gropuPcApiType)
Copy the code

The above code provides a variable named “gropuPcApiType” in the browser environment, which can be retrieved from js. The value of this variable is the value of the startup environment: development or development

Seven, case – sensitive – paths – webpack – the plugin

Enforces the entire path of all required modules, matching the exact case of the actual path on disk. That is, you can ignore the case problem to avoid the trouble caused by the case problem. Sometimes you’ll find that webpack builds fine on A Mac, but not on a Linux machine. This is because Macs are case insensitive. Avoid using the case-sensitive paths-webpack-plugin module

const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin')

new CaseSensitivePathsPlugin()
Copy the code

Eight, NamedModulesPlugin

In hot loading, return the name of the updated file instead of the ID. This is used in production environments:

new webpack.HotModuleReplacementPlugin(),
Copy the code

Resolve, see the next section: WebPack builds react development project 2 from scratch