1. The NPM initialization

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

2. Create a directory structure



(Easy version, for reference only)

3. Configure the mode, import file, and output file

const path = require("path"); Module. exports = {exports mode development \ production mode: "development", // exports file entry: Resolve (__dirname, "SRC /index.js"), // Output: {path: path.resolve(__dirname, "build"), filename: "build.[contenthash:10].js", }, }Copy the code

4. Introduce the HtmlWebpackPlugin

The plugin will generate an HTML5 file for you, importing all of your WebPack-generated bundles using the Script tag in the body.

const HtmlWebpackPlugin = require("html-webpack-plugin"); Module. exports = {plugins:[new HtmlWebpackPlugin({// HtmlWebpackPlugin: {//})} Path.resolve (__dirname, "public/index.html"), // package the generated HTML filename filename: "Index.html ", // collapse HTML file minify:{// Remove space collapseWhitespace: true, // remove comment removeComments: true,}})]}Copy the code

5. Introduce the CleanWebpackPlugin

Used to delete/clean up the previous build folder.

const { CleanWebpackPlugin } = require("clean-webpack-plugin");

module.exports={
    plugins:[
        new CleanWebpackPlugin()
    ]
}
Copy the code

6. Configuration webpack – dev – server

Use WebPack with a development server that provides real-time reloading, bringing its own HMR functionality.

  • — Open: automatically opens the browser, and then adds the corresponding browser name to open different browsers
  • — Port 3000: indicates the port running at 3000
  • — Progress: indicates progress
  • –host: specifies the port number. The default port number is localhost. You can change the port number by adding a space and a port number to –host 129.0.0.1

Add dev configuration to package.json file. (This error is most likely due to incompatible versions of Webpack-dev-server and webpack-CLI.)

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack-dev-server --config webpack.config.js --progress  --port 8000",
    "webpack": "webpack --progress"
},
Copy the code

7. Configure the loader based on the style

When there are multiple Loaders to process a file, the order of execution is array from right to left.

CSS styles (style-loader, CSS-loader)

module.exports = {
    module:{
        rules:[
            {
                test:/\.css$/,
                use:['style-loader','css-loader']
            }
        ]
    }
}
Copy the code

Less style (style-loader, CSS-loader, less-loader)

module.exports = {
    module:{
        rules:[
            {
                test:/\.less$/,
                use:['style-loader','css-loader','less-loader']
            }
        ]
    }
}
Copy the code

8. Configure style related plug-ins to optimize style packaging

Using MiniCssExtractPlugin

Extract CSS from packed JS files to speed up page responsiveness

const MiniCssExtractPlugin = require("mini-css-extract-plugin"); Module. Exports = {module: {rules: [{$/ test: / \. CSS, use: [/ / to pick up the style MiniCssExtractPlugin. Loader, "CSS - loader"]}. {test: / \. Less $/, use: [/ / to pick up the style MiniCssExtractPlugin. Loader, "CSS - loader", 'less - loader]}}, plugins:[ new MiniCssExtractPlugin({ filename: "bundle.[contenthash:10].css", }) ] }Copy the code

Use postcss – loader

Make styles compatible with different browsers

webpack.config.js

const CommonCss = [ MiniCssExtractPlugin.loader, "css-loader", { loader: "postcss-loader", options: { postcssOptions: {/ / auto-complete prefix plugins: [[" postcss - preset - env "]],},},},]; module.exports = { module:{ rules:[ { test:/\.css$/, use:[...CommonCss] }, { test:/\.less$/, use:[...CommonCss,'less-loader'] } ] } }Copy the code

package.json

The configuration requires compatible browsers

"Browserslist ": [">=1%", // share > 1%" last 2 versions" // latest two versions]Copy the code

Using OptimizeCssAssetsWebpackPlugin

Compressed and packaged CSS style files

const OptimizeCssAssetsWebpackPlugin = require("optimize-css-assets-webpack-plugin");

module.exports={
    plugins:[
        new OptimizeCssAssetsWebpackPlugin()
    ]
}
Copy the code

9. Configure image-related loader (url-loader, file-loader)

module.exports = { module:{ rules:[ { test:/\.(png|jpg|gif)$/, loader: "Url-loader ", options:{// If the size of the image is less than 8K, base64 processing will be used to reduce the request for the image limit: 8 * 1024, name: path.posix.join("images/[hash:10].[ext]"), } } ] } }Copy the code

10. Configure JS loader (babel-loader, core-js)

Module. exports = {module:{rules:[// @babel/preset-env: basic JS compatibility // core-js is used to do browser compatibility and speed up the page response {test:/\.js$/, include: path.resolve(__dirname, "src"), loader: "babel-loader", options:{ presets:[ [ "@babel/preset-env", { useBuiltIns: "usage", corejs:{ version: 3,}, targets:{chrome: "60", IE: "8", edge: "17",}}]], // enable Babel cacheDirectory on second build true, } } ] } }Copy the code

11. Configure TS-related loaders (babel-loader, TS-loader).

npm install --save-dev typescript @types/react @types/react-dom ts-loader

module.exports = {
    module:{
        rules:[
            {
                test:/\.js$/,
                include: path.resolve(__dirname, "src"),
                use: ["babel-loader", "ts-loader"],
            }
        ]
    }
}
Copy the code

12. Configure the folder alias

module.exports={
    resolve:{
        alias:{
            "@assets": path.resolve(__dirname, "src/assets"),
            "@store": path.resolve(__dirname, "src/store"),
            "@style": path.resolve(__dirname, "src/style"),
        }
    }
}
Copy the code

13. Separate and package code blocks

Module.exports ={// code split code // package the imported code separately into a chunk output optimization:{splitChunks:{chunks: "all",}}}Copy the code

14.source-map

Provides techniques for mapping source code to built code.

Sourcemap is an information file that stores location information, that is, every position in the converted code corresponds to the position before the converted code.

Module.exports ={eval-source-map is recommended for development environment // source-map is recommended for production environment // source-map is recommended for production environment // source-map is recommended for development environment // Source-map is recommended for development environment // / Source-map is recommended for production environment // Nosource-map/hidden-source-map devtool: "eval-source-map",}Copy the code