Refer to the WebPack tutorial and create-React-app (after eject) configuration to customize a suitable, maintainable WebPack configuration

1. Initialization

yarn init
Copy the code

Initialization succeeded

Yarn init V1.17.3 Question name (my-webpack-config): question version (1.0.0): question description: question entry point (index.js): question repository url (https://github.com/1071942338/my-webpack-config.git): Question author (Zhang Wenqi <[email protected]>): Question license (MIT): question private: Success Saved package.json ✨ Done in 10.97sCopy the code

2. Install webpack webpack-CLI

yarn add webpack webpack-cli -D
Copy the code

3. Package. json Add the build script

3.1 Adding the index.js file

  1. Creating a SRC folder
  2. Create a new index.js file
console.log("Hello Webpack !" );Copy the code

3.2 Adding the webpack.config.js file

  1. Creating a Config folder
  2. Create a new webpack.config.js file
Module.exports = {// specify entry: "./ SRC /index.js", output: {// specify filename: "main.js",}, // specify development mode: "development", };Copy the code

3.3 package.json Add scripts to build

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

3.4 Executing the Build Script

yarn build
Copy the code
Yarn run v1.17.3 $webpack -- config. / config/webpack config. Js Hash: 33226 b34c0395d779dc7 Version: webpack 4.44.1 Time: 47ms Built at: 2020/08/10 PM 2:31:51 Asset Size Chunks Names main.js 3.8 KiB main [emitted] main Entrypoint main = main.js [./ SRC /index.js] 32 bytes {main} [built] ✨ Done in 0.60s.Copy the code

3.5 Execution Result

  1. Generate folder dist
  2. Generate main.js file in dist directory
  3. Add the index.html file to the dist directory and use main.js. You can see the print on the console: Hello Webpack!

4. Split webpack. Config. Js

4.1 Purpose of Splitting

  • The requirements of development and production environments are different. For example, development requires hot updates to see the effect of the code, while generation requires compressed code
  • Easy to maintain

4.2 Split Results

  • Webpack.base.js common configuration
  • Webpack.dev.js develops the development configuration
  • Webpack.prod.js generates the environment configuration

4.3 Splitting Tools

You need webpack-merge

yarn add webpack-merge -D
Copy the code

4.3 Modify the file

<! -- webpack.base.js --> module.exports = {// specify entry: "./ SRC /index.js", output: "main.js", }, }; <! -- webpack.dev.js --> const { merge } = require("webpack-merge"); const baseConfig = require("./webpack.base"); module.exports = merge(baseConfig, { mode: "development", }); <! -- webpack.prod.js --> const { merge } = require("webpack-merge"); const baseConfig = require("./webpack.base"); module.exports = merge(baseConfig, { mode: "production", });Copy the code

4.3 Modifying the package.json file Contents

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

4.4 Execute commands separately

yarn dev <! -- or --> YARN BuildCopy the code

Dist /main.js files were generated, the difference being that dev was develpode-mode and the code was uncompressed.

5. Use HTML templates

yarn add html-webpack-plugin -D
Copy the code

5.1 Adding the index.html file

  1. Create a public folder
  2. Create a new index.html file
<! DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <title>my-webpack-config</title> <meta name="viewport" content="width=device-width, initial-scale=1" /> </head> <body></body> </html>Copy the code

5.2 Modifying the webpack.base.js file

const pathsUtil = require("./pathsUtil"); const HtmlWebpackPlugin = require("html-webpack-plugin"); Module.exports = {// specify entry: pathsutil. appIndexJs, output: {// export filename: "main.js",}, plugins: [ new HtmlWebpackPlugin({ template: pathsUtil.appHtml, inject: true, }), ], };Copy the code

5.3 Run the build command to view the automatically generated index.html file

<! DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <title>my-webpack-config</title> <meta name="viewport" content="width=device-width, initial-scale=1" /> </head> <body><script src="main.js"></script></body> </html>Copy the code

6. Add CSS support

yarn add style-loader css-loader -D
Copy the code

6.1 Adding the index. CSS file

.color {
  color: rebeccapurple;
}
Copy the code

6.2 Modifying the index.js file

import "./index.css";

const colorElement = document.createElement("div");
colorElement.setAttribute("class", "color");
colorElement.innerText = "my-webpack-config";
document.body.appendChild(colorElement);
Copy the code

6.3 Modifying the webpack.base.js file

const pathsUtil = require("./pathsUtil"); const HtmlWebpackPlugin = require("html-webpack-plugin"); Module.exports = {// specify the entry file entry: pathsutil. appIndexJs, output: {// export file filename: "main.js",}, module: {rules: [ { test: /\.css$/, use: ["style-loader", "css-loader"], }, ], }, plugins: [ new HtmlWebpackPlugin({ template: pathsUtil.appHtml, inject: true, }), ], };Copy the code

7. Add image support

yarn add url-loader file-loader -D
Copy the code

7.1 Add pictures of different sizes

  • small 47K
  • The big 4.4 M

7.2 Modifying the webpack.base.js file

const pathsUtil = require("./pathsUtil"); const HtmlWebpackPlugin = require("html-webpack-plugin"); Module.exports = {// specify the entry file entry: pathsutil. appIndexJs, output: {// export file filename: "main.js",}, module: {rules: [ { test: /\.css$/, use: ["style-loader", "css-loader"], }, { test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/], use: [ { loader: "url-loader", options: { limit: 51200,//50k }, }, ], }, ], }, plugins: [ new HtmlWebpackPlugin({ template: pathsUtil.appHtml, inject: true, }), ], };Copy the code

7.3 Modifying the index.js File

import "./index.css";
import smallImage from "./image/small.png";
import bigImage from "./image/big.png";

const colorElement = document.createElement("div");
colorElement.setAttribute("class", "color");
colorElement.innerText = "my-webpack-config";
document.body.appendChild(colorElement);

const smallImageElement = document.createElement("img");
smallImageElement.setAttribute("src", smallImage);
document.body.appendChild(smallImageElement);

const bigImageElement = document.createElement("img");
bigImageElement.setAttribute("src", bigImage);
document.body.appendChild(bigImageElement);

Copy the code

7.4 View the build package in the Browser

  • Small is displayed as a string of Base64
  • Big 4.4m is displayed as a path-loaded picture

8. Add font parsing

yarn add file-loader -D
Copy the code

8.1 modify the index. The CSS

.color {
  color: rebeccapurple;
}
@font-face {
  font-family: myFirstFont;
  src: url("./font/font.ttf");
}
.font {
  font-family: myFirstFont;
}

Copy the code

8.2 modify the index. Js

import "./index.css";
import smallImage from "./image/small.png";
import bigImage from "./image/big.png";

const colorElement = document.createElement("div");
colorElement.setAttribute("class", "color");
colorElement.innerText = "my-webpack-config";
document.body.appendChild(colorElement);

const fontElement = document.createElement("div");
fontElement.setAttribute("class", "color font");
fontElement.innerText = "my-webpack-config";
document.body.appendChild(fontElement);

const smallImageElement = document.createElement("img");
smallImageElement.setAttribute("src", smallImage);
document.body.appendChild(smallImageElement);

const bigImageElement = document.createElement("img");
bigImageElement.setAttribute("src", bigImage);
document.body.appendChild(bigImageElement);

Copy the code

8.3 modify the webpack. Base. Js

const pathsUtil = require("./pathsUtil"); const HtmlWebpackPlugin = require("html-webpack-plugin"); Module.exports = {// specify the entry file entry: pathsutil. appIndexJs, output: {// export file filename: "main.js",}, module: {rules: [ { test: /\.css$/, use: ["style-loader", "css-loader"], }, { test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/], use: [ { loader: "url-loader", options: { limit: 51200, //50k }, }, ], }, { test: /\.(woff|woff2|eot|ttf|otf)$/, use: ["file-loader"], }, ], }, plugins: [ new HtmlWebpackPlugin({ template: pathsUtil.appHtml, inject: true, }), ], };Copy the code

8.4 Build package to view the effect

9. Add React support

9.1 Adding Babel support

yarn add @babel/core @babel/preset-env @babel/preset-react -D
Copy the code

9.2 Adding Babel-Loader Support

yarn add babel-loader -D
Copy the code

9.3 Adding Support for React

yarn add react react-dom 
Copy the code

9.4 modify the webpack. Base. Js

yarn add react react-dom 
Copy the code

9.5 modify the index. HTML

<! DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <title>my-webpack-config</title> <meta name="viewport" content="width=device-width, initial-scale=1" /> </head> <body> <div id="root"></div> </body> </html>Copy the code

9.6 modify the index. Js

import React from "react";
import ReactDom from "react-dom";
import "./index.css";
import App from "./App.jsx";

ReactDom.render(<App />, document.getElementById("root"));

Copy the code

9.7 the new App. JSX

import React from "react"; import smallImage from "./image/small.png"; import bigImage from "./image/big.png"; export default class App extends React.Component { render() { return ( <div> <div className="color">my-webpack-config</div> <div className="color font">my-webpack-config</div> <img src={smallImage} alt=""></img> <img src={bigImage} alt=""></img> </div> ); }}Copy the code

9.9 Run the build script and check the result

10. Automatically compile code

yarn add webpack-dev-server -D

Copy the code

10.1 Adding the scripts folder

  • New dev. Js
  • The new build. Js

10.2 edit dev. Js

"use strict"; const webpack = require("webpack"); const prodConfig = require(".. /config/webpack.dev.js"); const webpackDevServer = require("webpack-dev-server"); const compiler = webpack(prodConfig); const devServerOptions = Object.assign({}, prodConfig.devServer, { open: true, stats: { colors: true, }, }); const server = new webpackDevServer(compiler, devServerOptions); Listen (3000, "127.0.0.1", () => {console.log("Starting server on http://localhost:3000"); });Copy the code

10.3 edit the build. Js

"use strict"; const webpack = require("webpack"); const prodConfig = require(".. /config/webpack.prod.js"); Webpack (prodConfig, (err, stats) = > {the if (err | | stats. HasErrors ()) {/ / processing error console. Here the log (" err: "err); console.log("stats:", stats); } // finish console.log(" finish "); });Copy the code

10.4 Editing the Package. json File

  "scripts": {
    "dev": "node ./scripts/dev.js",
    "build": "node ./scripts/build.js"
  },
Copy the code

10.5 Run the Build script and check the result

yarn dev
Copy the code

Then the http://localhost:3000 page is automatically opened. After the edited page is saved, the page is automatically refreshed


Code warehouse

  • my-webpack-config

Refer to the link

  • The installation
  • start
  • Management resources
  • The development of
  • In the development Server (devServer)
  • webpack webpack-dev-server
  • url-loader
  • file-loader
  • css-loader
  • style-loader
  • css-loader
  • babel-loader
  • Babel Usage Guide
  • babel-preset-react
  • html-webpack-plugin