preface

Before that, I used existing scaffolding to start a new project, which is very convenient to start a new project quickly, and universal scaffolding is usually more comprehensive, which is conducive to the stable development of the project; However, for a small project, it may be better to build it according to the needs. On the one hand, the small project does not need the rich functions of scaffolding, and on the other hand, the control degree of the project can be improved to facilitate the later expansion.

This article is summarized in practice, with practical operation, readers can follow step by step to build, I will intersperse some principles, of course, because of the author’s limited ability, not particularly in-depth.

Preliminary knowledge

  • Familiar with Javascript & HTML & CSS
  • Be familiar with the ES6 +
  • Ability to build Nodejs environment
  • Command line

The target

  • Learn to use webpack5 and why
  • Build the development environment with webpack5
  • Build the production environment with Webpack5

What is a webpack

This is a bit of a cliche, but for the sake of new students can read down, here is a brief introduction. A modern Web application is no longer simply composed of excellent HTML, CSS and javascript. It also needs to package, compress and compile the application into a code that the browser can understand, so Webpack began to be popular.

Webpack is a module packer that can package anything. You can develop with the latest Javascript features or Typescirpt, and WebPack compiles it into browser-supported code and compresses it. You can also import the static resources you need in Javascript.

During development, WebPack provides the development server and supports HMR. What HMR is and how to configure it will be explained later, but for now we just need to know that WebPack will automatically recompile and refresh the browser when we save the code.

Webpack does much more than that, and this article will help you familiarize yourself with the basics and how to configure your own scaffolding.

Begin to build

This article is a fairly complete hands-on tutorial. The goal is to build a working scaffolding from which to extend more functionality.

Features the architecture needs to support

  • Webpack5

  • Command line friendly prompt

  • es6+

  • React

  • Typescript

  • PostCSS + cssnext

  • HMR

Install webpack

Create a new project, go to the project root directory, and create the default package.json

yarn init -y
Copy the code

Install Webpack and WebPack-CLI

  • webpack– Module packaging library
  • webpack-cli– Command line tool
yarn add webpack webpack-cli -D
Copy the code

Basic configuration

Create a new webpack.config.js file in the root directory

Entry

Entry file, where WebPack will compile first

// webpack.config.js
const path = require('path');

module.exports = {
  entry: {
    app: './src/index.js'}},Copy the code

Output

Defines the location of the packaged output and the corresponding file name. [name] is a placeholder, which is equivalent to app according to the key value defined in Entry

module.exports = {
  / *... * /

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

Make sure you have index.js under SRC, and now you can package it using our minimal configuration. Add the following code to package.json

"scripts": {
  "build": "webpack"
}
Copy the code

Run the command

yarn run build
Copy the code

You can see the result of the packaging on the command line, with a dist directory generated in the root directory, indicating that the packaging was successful.

Plugins

Plug-ins make WebPack extensible and allow us to support more functionality.

Template file

When we build a Web app, we need an HTML page, and then we introduce Javascript into the HTML. When we configure the bundle output to be a random string, it is very cumbersome to manually update the bundle every time, so the best way is to automatically package the bundle into HTML.

  • Html-webpack-plugin – Generates an Html file from the template

The installation

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

Create a new file public/index.html in the root directory with the following contents

<! DOCTYPEhtml>
<html lang="en">
  <head>
    <title><%= htmlWebpackPlugin.options.title %></title>
  </head>

  <body>
    <div id="root"></div>
  </body>
</html>
Copy the code

Where title is the configuration of the htML-webpack-plugin plug-in, which is configured as follows

// webpack.config.js

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  / *... * /

  plugins: [
    new HtmlWebpackPlugin({
      title: 'Tiemuzhen Large Screen Display'.template: path.resolve(__dirname, './public/index.html'),
      filename: 'index.html',})],}Copy the code

Now run YARN Run build again and you can see that there is an index. HTML file under dist with the title and script automatically inserted as follows

Clear before packingdist

  • clean-webpack-plugin– Remove/clear packing directories before packing

The installation

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

configuration

const path = require('path')

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

module.exports = {
  / *... * /

  plugins: [
    / *... * /
    new CleanWebpackPlugin(),
  ],
}
Copy the code

Command line friendly prompt

The installation

yarn add friendly-errors-webpack-plugin -D
Copy the code

configuration

// webpack.config.js
const friendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');

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

Loaders

Webpack uses loaders to parse modules, and webPack needs to configure loader rules to understand Javascript, static resources (images, fonts, CSS), Typescript, and Babel.

Having just one HTML and some Javascript in a project doesn’t help, we also need WebPack to be able to do a few things:

  • Compile the latest Javascript features into ones that the browser understands
  • Modular CSS, will compile SCSS, CSSNext to compile CSS
  • Import static resources such as images and fonts
  • Use your favorite framework, like React

Babel

Babel is a JavaScript compiler that can convert ES6 code into ES5 code, allowing you to use the latest language features without worrying about compatibility, and can be flexibly extended on demand through the plug-in mechanism. We need to install the following libraries first

yarn add babel-loader @babel/core -D
Copy the code
  • babel-loader– Use Babel and Webpack to translate files
  • @babel/core– Translate ES2015+ code

Configuration is as follows

// webpack.config.js
module.exports = {
  / *... * /

  module: {
    rules: [
      // JavaScript
      {
        test: /\.m? js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'.options: {
            presets: ['@babel/preset-env'],},},},],},}Copy the code

During compilation by Babel, the configuration is read from the configuration file in the project root directory. Create the Babel configuration file babel.config.json in the root directory

{
  "presets": ["@babel/preset-env"]}Copy the code

If @babel/preset-env is not installed, install it first

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

Images and Fonts

Loader configuration to parse images

module.exports = {
  / *... * /
  module: {
    rules: [
      // Images
      {
        test: / \. (? :ico|gif|png|jpg|jpeg)$/i,
        type: 'asset/resource',},],},}Copy the code

Loader configuration to parse font files

module.exports = {
  / *... * /
  module: {
    rules: [
      // Fonts and SVGs
      {
        test: /\.(woff(2)? |eot|ttf|otf|svg|)$/,
        type: 'asset/inline',},],},}Copy the code

style

Now we want to be able to import CSS in Javascript, inject CSS into the DOM, and use advanced CSS features, such as CSSNext, that rely on libraries

  • Css-loader – Resolves CSS imports

  • Style-loader – Inserts CSS into the DOM

  • Postcss-loader – Uses postCSS to process CSS

    • postcss-preset-env– PostCSS default configuration
  • Postcss – PostCSS is a tool that allows you to transform styles using JS plug-ins. Lint these plugins examine your CSS, support CSS Variables and Mixins, compile advanced CSS syntax not yet widely supported by browsers, inline images, and many other nice features.

  • Postcss-next-postcss plugin that can use the latest CSS syntax

The installation

yarn add css-loader style-loader postcss-loader postcss-preset-env postcss postcss-cssnext -D
Copy the code

Create the PostCSS configuration file postcss.config.js

module.exports = {
  plugins: {
    'postcss-preset-env': {
      browsers: 'last 2 versions',,}}}Copy the code

Configure the loader

// webpack.config.js

module.exports = {
  / *... * /
  module: {
    rules: [
      // CSS, PostCSS, and Sass
      {
        test: /\.(scss|css)$/,
        use: ['style-loader', {
            loader: 'css-loader'.options: {
              importLoaders: 1,}},'postcss-loader'],},],},}Copy the code

The development environment

Let’s start by setting the configuration to development mode, indicating that the current configuration is the configuration of the development environment

// webpack.config.js

module.exports = {
 mode: 'development'.// ...
}
Copy the code

Use the source maps

In order to better track the code when an error is reported and give a hint of where the error code occurs, we can use the source map, configured as follows

// webpack.config.js

module.exports = {
 devtool: 'inline-source-map'
 // ...
}
Copy the code

HMR

Webpack provides three different ways to automatically recompile code when we change it:

  1. Listening mode
  2. webpack-dev-server
  3. webpack-dev-middleware

In most cases, you use Webpack-dev-server, and this article will use that as well, but I’ll mention the other two in passing, so you can take what you want.

  • Using listening mode:
// package.json
{
  "watch": "webpack --watch"
}
Copy the code

Execute the following command

yarn run watch
Copy the code

The code is now compiled automatically when we save it and can be seen after refreshing the browser; But if we want to automatically refresh the browser, it’s the webpack-dev-server store’s turn.

  • webpack-dev-server

It provides us with a server and live Relaoding capabilities that we need to install first

yarn add webpack-dev-server -D
Copy the code

Then configure the following

// webpack.config.js
module.exports = {
  // ...
  devServer: {
    historyApiFallback: true.contentBase: path.join(__dirname, './dist'),
    open: false.hot: true.quiet: true.port: 8082,}}Copy the code
// package.json
{
  "scripts": {
    "start": "webpack serve"}}Copy the code

We monitored a service on port 8082, the listening directory is dist and supports HMR. Now open http://localhost:8082, you can see our page, and then change the code, the browser will automatically refresh and update the effect, isn’t it cool?

Mentioned above, HMR stands for Hot Module Replacement, and I think it’s one of the most useful features webPack provides. It allows us to update only the changed modules without having to update all of them. We’ve already enabled this feature above, namely Hot: True.

  • webpack-dev-middleware

This is a webPack middleware that allows WebPack to hand over files to a server for processing, such as express, which we’ll use next. This gives us more control, as we’ll briefly demonstrate.

Install Express and Webpack-dev-Middleware

yarn add express webpack-dev-middleware -D
Copy the code

Change the configuration

module.exports = {
  / /...
  output: {
    / /...
    publicPath: '/'}}Copy the code

PublicPath can define the path of the Express listening service. Next, we will create our Express server

Create a new server.js file

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 the webpack-dev-middleware and use the webpack.config.js
// configuration file as a base.
app.use(
  webpackDevMiddleware(compiler, {
    publicPath: config.output.publicPath,
  })
);

// Serve the files on port 3000.
app.listen(3000.function () {
  console.log('Example app listening on port 3000! \n');
});
Copy the code

If the listening port is 3000, run the following command to start the service

node server.js
Copy the code

For convenience, you can add this command to package.json

{
  / /...
  "scripts": {
    "server": "node server.js"}}Copy the code

Use the Typescript

Install dependencies

yarn add typescript ts-loader -D
Copy the code

Create the typescript configuration file tsconfig.json in the root directory as follows

{
  "compilerOptions": {
    "outDir": "./dist/".// "rootDir": "./src",
    "sourceMap": true./ / open sourcemap
    "module": "commonjs"."target": "es5"."jsx": "react"."esModuleInterop": true."allowJs": true."strict": true}}Copy the code
// webpack.config.js
module.exports = {
  / /...
  module: {
    rules: [{test: /\.tsx? $/,
        use: 'ts-loader'.exclude: /node_modules/,},]}}Copy the code

Use the React

In configuring typescript above, you already have React support enabled, so now you just need to install the React dependencies

yarn add react react-dom @types/react @types/react-dom
Copy the code

Then change the entry file to the.tsx suffix with the following content

import React from 'react';
import ReactDOM from 'react-dom';

import './index.css';

const App = () = > {
  return <div>hello world2</div>;
};

ReactDOM.render(<App />.document.getElementById('root'));
Copy the code

Code specification

Prettier

Prettier is a tool for formatting code that became popular in 2016. -. -Prettier only cares about formatting, doesn’t have lint syntax check, etc. It enforces a consistent code presentation format by parsing the code and matching its own set of rules. It has the advantage of beautifying code, and working with ESLint can be a nice complement to ESLint formatting.

use

Take VSCode as an example, the plug-in for Prettier can be used. If you want to customize VSCode, go to CMD + to search for Prettier and configure it.

Eslint

ESLint is a plug-in detection tool that identifies and reports code in JavaScript code through rule pattern matching. The purpose of ESLint is to ensure code specification consistency and to find problems in code before errors occur. ESLint is concerned with code quality, checking code styles and prompting code that does not conform to style specifications. ESLint also has some code formatting capabilities.

Install dependencies and, for convenience, use the existing Eslint configuration directly, in this case Fabric

yarn add @umijs/fabric -D
Copy the code

Create.eslintrc.js in the root directory

module.exports = {
  extends: [require.resolve('@umijs/fabric/dist/eslint')].globals: {},
  plugins: ['react-hooks'].rules: {
    'no-restricted-syntax': 0.'no-param-reassign': 0.'no-unused-expressions': 0,}};Copy the code

Restart the editor to apply the Eslint configuration.

conclusion

So far, we’ve built a simple React scaffolding that supports typescript, CSSNext, HMR, etc. It’s enough for a small project, so you can expand on it. If there is time behind, I will discuss the underlying principle of Webpack with you, from the perspective of the source code.

The appendix

how-to-use-webpack

Webpack website