Connected to aFrom zero to one Learn Webpack 01 – WebPack building applications

In the last article, we implemented a basic WebPack configuration that meets our basic needs for JSX and CSS extraction, dependency file extraction, and automatic build execution that monitors changes to our code in real time.

However, we couldn’t develop the project this way — by opening up locally generated index.html — so we needed a development environment that made the development experience more friendly

Setting up the development environment

Note: we have set webpack.config.js mode to development.

First, we configure devtool: ‘inline-source-map’ to enable source-map. Source-map is very useful for development debugging to locate error code directly

Use the webpack – dev server. –

Webpack-dev-server gives you a simple web server with real-time reload (real-time reload) capability

yarn add webpack-dev-server -D

Modify the configuration file to tell the dev server where to look for the file:

const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');


module.exports = {
  entry: "./src/index.js".output: {
    path: path.resolve(__dirname, "dist/"),
    filename: "[name].bundle.js"
  },
  mode: "development".devtool: 'inline-source-map'.devServer: {
    contentBase: './dist',},module: {
    rules: [{test: /\.(js|jsx)$/,
        exclude: /(node_modules|bower_components)/,
        loader: "babel-loader".options: { presets: ["@babel/env"]}}, {test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, "css-loader"]]}},resolve: { extensions: ["*".".js".".jsx"]},plugins: [
    new CleanWebpackPlugin(),
    new MiniCssExtractPlugin(),
    new HtmlWebpackPlugin({
      title: 'Manage output'.template: './public/index.html'}),].optimization: {
    splitChunks: {
      chunks: 'all',}}};Copy the code

This configuration tells webpack-dev-server to service files in dist to localhost:8080.

Webpack-dev-server provides a bundle file for the service from the directory defined in output.path, that is, The file can be accessed through http://[devserver.host]:[devserver. port]/[output.publicpath]/[output.filename].

Let’s add a script to run dev Server directly in package.json:

."scripts": {
    "watch": "webpack --watch"."dev": "webpack serve --open"."build": "webpack"}...Copy the code

Try yarn dev to see the effect

Update the code in the SRC folder and the page will refresh automatically

Use the webpack – dev – middleware

Webpack-dev-middleware is a wrapper that sends webPack-processed files to a server. Webpack-dev-server uses it internally, but it can also be used as a separate package

First, install Express and Webpack-dev-Middleware

yarn add webpack-dev-middleware -D

yarn add express

To use webpack-dev-middleware as middleware, we need to modify the output configuration of webpack.config.js

  output: {
    path: path.resolve(__dirname, "dist/"),
    filename: "[name].bundle.js".publicPath: '/',}Copy the code

We will use publicPath in the server script to ensure that the file resources are properly placed at http://localhost:3000. Later we will specify the port number (port number) and then set custom

Express server: Add a server.js file server.js to the root directory

const express = require('express');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');

const app = express();
const config = require('./webpack.config.js');
const compiler = webpack(config);

// Tell Express to use webpack-dev-middleware,
// And use the webpack.config.js configuration file as the base configuration.
app.use(
  webpackDevMiddleware(compiler, {
    publicPath: config.output.publicPath,
  })
);
// Serve the file to port 3000.
app.listen(3000.function () {
  console.log('Example app listening on port 3000! \n');
});
Copy the code

Now, add an NPM script to make it easier to run the server:

  "scripts": {
    "watch": "webpack --watch"."dev": "webpack serve --open"."server": "node server.js"."build": "webpack"
  },
Copy the code

Try running YARN Server

Now, open your browser and visit http://localhost:3000 and you should see the WebPack application running! Updating the SRC code shows that webpack is running again on the terminal, but the page is not refreshed in real time (requiring a manual refresh of the page). This is because webpack-dev-middleware also requires HMR configuration (== development environment only ==).

HMR

Hot Module Replacement (or HMR) is one of the most useful features webPack provides. It allows all types of modules to be updated at run time without a complete refresh

Enable the HMR

If you use Webpack-dev-middleware instead of Webpack-dev-server in your technology selection, Use the Webpack-hot-Middleware dependency package to enable HMR on your custom server or application

Webpack-hot-middleware is used with webpack-dev-middleware ==

yarn add webpack-hot-middleware -D
Copy the code

There are a few changes that need to be made:

  1. Webpack. Config. Js need to increase the entry documents, increased webpack plugins HotModuleReplacementPlugin
.entry: ["./src/index.js".'webpack-hot-middleware/client'],...plugins: [
    new CleanWebpackPlugin(),
    new MiniCssExtractPlugin(),
    new HtmlWebpackPlugin({
      title: 'Manage output'.template: './public/index.html'
    }),
    new webpack.HotModuleReplacementPlugin()
  ],
...
Copy the code
  1. Server. In js
const express = require('express');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware')

const app = express();
const config = require('./webpack.config.js');
const compiler = webpack(config);

// Tell Express to use webpack-dev-middleware,
// And use the webpack.config.js configuration file as the base configuration.
app.use(
  webpackDevMiddleware(compiler, {
    publicPath: config.output.publicPath,
  })
);

app.use(webpackHotMiddleware(compiler, {
  path: '/__webpack_hmr',}));// Serve the file to port 3000.
app.listen(8080.function () {
  console.log('Example app listening on port 3000! \n');
});
Copy the code

3. One more important point: the entry file needs to tell WebPack to allow hot updates to this module to be added at the end of SRC /index.js

It is important to note that WebPack allows hot updates to this module
if (module.hot) {
    module.hot.accept();
}
Copy the code

Run yarn Server again, and you are done!

Through the Node. Js API

== First of all, restore webpack-hot-middleware to be used with webpack-dev-middleware in three steps

When using WebPack Dev Server in the Node.js API, do not place the dev Server option in the WebPack configuration object. Instead, it is passed as the second parameter when it is created. For example: New WebpackDevServer(Compiler, options). If you want to enable HMR, you also need to modify the WebPack configuration object to include the HMR entry starting point. The WebPack-dev-server dependency package has a method called addDevServerEntrypoints that you can use to do this

Add dev-server.js to the root directory

const webpackDevServer = require('webpack-dev-server');
const webpack = require('webpack');

const config = require('./webpack.config.js');
const options = {
  contentBase: './dist'.hot: true.host: 'localhost'}; webpackDevServer.addDevServerEntrypoints(config, options);const compiler = webpack(config);
const server = new webpackDevServer(compiler, options);

server.listen(5000.'localhost'.() = > {
  console.log('dev server listening on port 5000');
});
Copy the code

In the package. The json

  "scripts": {
    "watch": "webpack --watch"."dev": "webpack serve --open"."server": "node dev-server.js".// Notice that the code executed after yarn server is dev-server.js
    "build": "webpack"
  },
Copy the code

Executing YARN Server also serves our purpose of hot updates

In the next article, we’ll stock up on cachingLearn WebPack 03- Cache from zero to one