Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities

This article also participated in the “Digitalstar Project” to win a creative gift package and creative incentive money

preface

In this section, we will guide you to add image processing functions in Webpack, distinguish between production environment and development environment, explain the configuration of Devtool, clean dist directory before packaging and compilation, PostCSS to deal with browser compatibility issues, ESLint configuration, Bring our Webpack into shape. The source address for this issue is webpack02

There are Easter eggs at the end 😝


The build process


Working with image files

Images are often used in projects. Whether they are introduced by URL () in CSS or imported by JS, the image function is essential. There are many common formats for images such as PNG, JPG, GIF, etc. Next we will use the function of adding loader to let Webpack pack the images. Yes, we can make WebPack support image packaging by simply adding a loader configuration to process images

There are two file-loader and url-loader commonly used by image. The following is the introduction of the two loaders

File-loader: if the imported file is a. PNG or. TXT file, you can use file-loader to parse the imported URL. Copy the file to the appropriate path according to the configuration, and modify the import path of the packaged file so that it points to the correct file.

Url-loader: url-loader encapsulates file-loader and can be used independently of file-loader. Limit can also be configured. For images smaller than limit, convert them to Base64. For images larger than limit, use file-loader.

First installation

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

Configure webpack.config.js and add it in rules

 {
        test: /\.(jpg|png|gif)$/,
        use: [
          {
            loader: "url-loader",
            options: {
              limit: 2 * 1024,
              name: "[name].[contenthash:8].[ext]",
              outputPath: "assets/images",
            },
          },
        ],
 }
Copy the code
  • “[name].[contenthash:8].[ext]” : indicates the output hash value, which is used to solve the cache problem of referenced images
  • OutputPath: indicates the path to output the image
  • Limit: Url-loader has all the functions of file-loader. The operation procedure in the following options is to package the images less than 10K into base64 files to reduce HTTP requests. The file larger than 2k is still used by file-loader. The size of Base64 in most projects is usually 2k, because base64 is usually 3/4 of the size of the image. Too much base64 can be much larger than the image, which can affect performance

Devtool configuration

Why use DevTool

Why is that? Because often the code we run in the browser is processed, the processed code can be very different from the development code, which makes development debugging and debugging on the line difficult. This is where the Source Map comes in, allowing the browser to navigate directly from the converted code to the pre-converted code. In Webpack, the Source Map can be configured using the devtool option.

How to configure more efficient, better

In most projects, the development environment uses eval-cheap-module-source-map, which also makes packaging faster. On the production side, you only need to know the module and line number of the error, so use nosource-source-map

Distinguish between development/production environments

Why distinguish between production and development environments

Because the production environment should be conducive to development and debugging and build development packages as quickly as possible, you can package.map files in the development environment for debugging. However, do not pack map files in a production environment, which will increase the size of the production package and sacrifice performance. The production environment should be compressed as much as possible, optimize the bundle files, and display them as quickly as possible.

First installation

yarn add webpack-merge --dev
Copy the code

Create a new config file in the root directory

Call the previously configured webpack.config.js file webpack.base.config.js and put it in the config file

Create the webpack.dev.config.js(development environment package) and weback.prod.config.js(production environment package) files in config

Directory as follows

The development environment

const { merge } = require("webpack-merge");
const base = require("./webpack.base.config");

module.exports = merge(base, {
  mode: "development",
});

Copy the code

The production environment

const { merge } = require("webpack-merge");
const base = require("./webpack.base.config");

module.exports = merge(base, {
  mode: "production",
});
Copy the code

Although both are configured separately, in the common configuration, there may be an option for one configuration to be used in a different configuration for development and production. We can differentiate between development and production by setting process.env.node_env, which is the current node environment, but there is a problem. Windows does not use the same commands as MAC or Liunx to set the node environment. In order to unify the commands, we can use cross-env to set the environment variables

yarn add cross-env
Copy the code

After installation, we can configure script like this in package.json

Let’s do something with this environment variable now! Remember that in the common configuration, we gave the name of the exit file hash:8, because in the production environment, the user is already visiting our page, and when he first visits, he requests a file such as app.js, which will be cached according to the browser’s cache policy. Then we developed the code to complete a version of the functionality iteration, involving a big change in the packaged app.js, but if the user continues to visit our page, if the cache time is not exceeded or the cache is not artificially cleared, then he will continue to get cached app.js, which is bad.

So, when we added the hash file, depending on the entry file content, the hash values will change very exaggerated, when update to online, the user request again, because the cache file can’t find the file with the same name, will get the latest files to the server data, this can ensure that users use the latest functions.

However, this hash value is not needed in the development environment, so we modify the webpack.base.config.js file:

const isDev = process.env.NODE_ENV ! == "production"; module.exports = { ... , output: { filename: `js/[name]${isDev ? "" : ".[hash:8]"}.js`, path: path.join(__dirname, ".. /dist"), }, ... };Copy the code

Clean up the dist directory before packing and compiling

When we pack, we always delete the dist directory before we pack a new package. Is there any way for Webpack to automatically clear the Dist directory for us before we pack? The answer is of course, WebPack is very considerate to provide this service. Just use the clean-Webpack-plugin

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

Just add the following code to your plugins to take effect

plugins: [

   new CleanWebpackPlugin(),

],
Copy the code

PostCSS handles browser compatibility issues

CSS properties like Flex often run into browser compatibility issues, so in this section we’ll use PostCSS to deal with browser compatibility issues

Postcss is a compilation tool for CSS, similar to Babel to JS through a variety of plug-ins for CSS processing, here we mainly use the following plug-ins:

  • Postcss-preset -env: Turn the latest CSS syntax into a CSS syntax that can be understood by the browser of the target environment in order to save the developer from browser compatibility concerns.
yarn add postcss-loader postcss-preset-env --dev
Copy the code

This configuration still doesn’t work, so we need to configure Browserslist in package.json

So it looks like this

{... "browserslist": [ "defaults", "not ie < 11", "last 2 versions", "> 1%", "iOS 7", "last 3 iOS versions" ], ... }Copy the code

This is the browser compatibility list configured so that the configuration works perfectly

Eslint configuration

Eslint is an integral part of engineering to make sure you’re writing code in a standardized way

Install it first

Eslint Main tool for lint code, so everything is based on this package. Babel-eslint dependencies allow you to use experimental features while still checking ESLint syntax. On the other hand, you don't need to install dependencies if your code doesn't use experimental features that Eslint doesn't support. Pre-commit Hooks run Lint-staged to perform code detection on files in Git staging before committing informationCopy the code
yarn install eslint babel-eslint pre-commit lint-staged --dev
Copy the code

Configuration file. eslintrc.js for reference

module.exports = {
  root: true.env: {
    browser: true.es6: true.node: true,},extends: "eslint:recommended".parser: "babel-eslint".rules: {
    "no-console": process.env.NODE_ENV === "production" ? "error" : "off"."no-debugger": process.env.NODE_ENV === "production" ? "error" : "off"."space-before-function-paren": 0,}};Copy the code

Package. json configuration reference

"scripts": {
    "lint:staged": "lint-staged"
  },
  "lint-staged": {
      "src/**/*.{ts,js}": [
        "eslint --fix"]},"pre-commit": "lint:staged".Copy the code

So ESLint can take effect

Thank you very much to see here, hard, ease ease eye fatigue, appreciate the beauty of the smile, 😝

Feel programmers should rarely watch TV, we know who this beauty is ❓ welcome to comment area message 👏🏻

Today this article has enriched our Webpack function, the next section will guide you to build React with WebPack, and improve the development environment and production environment configuration, come on, thank you!!

Refer to the article

  • [2.7W] React+Typescript project environment