This is the fourth day of my participation in the More text Challenge. For details, see more text Challenge

preface

In the Use of WebPack5 (I) : Starter article, I showed you how to manage HTML and JS, touching on attributes such as Entry, Output, and plugins. This article will add information on how to manage CSS, images and other resources, and how to use Loader.

The traditional way to load resources is to write the corresponding HTML tag to load resources, such as:

Load the CSS

Loading method 1: style tag

You need to install csS-Loader and style-Loader to load the CSS.

npm i -D css-loader style-loader
Copy the code

Css-loader is used to identify and load CSS, and style-Loader is used to convert CSS into HTML style nodes.

Webpack.config.js, we need to add a module property in which to configure loader.

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

Let’s create a CSS directory in the SRC directory, create a new directory in the CSS directory, and add test code in it.

body {
  background: yellowgreen;
}
Copy the code

Add imported CSS in index.js.

import '.. /css/index.css'
Copy the code

First test with NPM run dev, you can see the background color has changed, open the console, you can also see the style TAB added.

Let’s stop dev, run NPM run build, and open dist/index.html.

There doesn’t seem to be a

You can find a style code saying that

Loading mode 2: an independent CSS file

In general, we want the CSS code to be in a separate CSS file, separate from the HTML and JS, and the mini-css-extract-plugin is used to extract the CSS into a separate file.

npm i -D mini-css-extract-plugin
Copy the code

Since we have decided to use the mini-css-extract-plugin, style-loader is not needed.

webpack.config.js

const MiniCssExtractPlugin = require('mini-css-extract-plugin')

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

Run NPM run build. You can see that there is an extra main.css file in the dist directory, and the main.css file is automatically introduced into the index.html.

In addition, there is a plugin called extract-text-webpack-plugin that does the same thing, but it is no longer officially recommended for WebPack4 +.

Compress CSS code

Careful observers may notice that the JS code in the dist directory has been compressed, but the CSS code has not been compressed. Now we can use the CSS-minimizer-webpack-plugin to compress the CSS code.

Installing CSS – minimizer – webpack – the plugin

npm i -D css-minimizer-webpack-plugin
Copy the code

Note that since the development environment does not require compression code, we only need to write the compression configuration in webpack.prod.js.

webpack.prod.js

const { merge } = require('webpack-merge')
const common = require('./webpack.config.js')
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin')

module.exports = merge(common, {
  mode: 'production'.optimization: {
    minimizer: [
      new CssMinimizerPlugin(),
    ],
  },
})
Copy the code

If we re-build, we can see that our CSS code has been compressed

But let’s open main.js again. Yi? Why is JS not compressed?

The code in the official documentation looks like this, with a comment like this

optimization: {
    minimizer: [
      // In webpack@5, you can use '... 'syntax to extend the existing minimizer (that is,' terser-webpack-plugin ') by uncommenting the next line
      / / `... `,
      new CssMinimizerPlugin(),
    ],
},
Copy the code

Let’s try to uncomment the comment code by following the official code.

optimization: { minimizer: [// At webpack@5, you can extend the existing minimizer (i.e., 'terser-webpack-plugin') by using the '... 'syntax, Uncomment the next line '... ', new CssMinimizerPlugin(),],},Copy the code

Build again and you can see that the JS code is also compressed.

In WebPack5, the terser-webpack-plugin is automatically enabled in the production environment mode, that is, to compress js code. Webpack5 comes with the latest terser-webpack-Plugin, so there is no need to install and enable it. A bit of a puzzle here is why WebPack5 doesn’t include the CSS-Minimizer-Webpack-plugin as well. It’s also important to compress CSS code.

In addition, there is also a good plugin for compressed JS, uglifyjs-webpack-plugin. I didn’t go into the difference between uglifyjs-webpack-plugin and terser-webpack-plugin.

Load SCSS and sass

Install the sass sass – loader

npm i -D sass sass-loader
Copy the code

We added an extra rule to webpack.config.js to load SCSS and sass

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

Create an extra SCSS folder in SRC and an index. SCSS file with the test code in it.

body {
  background: burlywood;
}
Copy the code

Index. Js, the introduction of the index. SCSS

import '.. /scss/index.scss'
Copy the code

Build up.

Dist /main. CSS is found to introduce SCSS code, indicating that SCSS loading is successful.

Organize files

We found that the files in the dist directory were HTML, JS, and CSS in a mess that an actual deployed project would never have been.

Let’s adjust the configuration.

webpack.config.js

module.exports = {
    ...
    output: {
        filename: 'js/[name].[fullhash].js'. },plugins: [...new MiniCssExtractPlugin({
          filename: 'css/[name].[fullhash].css'})],... }Copy the code

The generated files are placed in different folders.

supplement

Loaders are loaded sequentially, for example

{
    test: /\.s[ac]ss$/i,
    use: [
      MiniCssExtractPlugin.loader, 'css-loader'.'sass-loader']}Copy the code

Loading sequence: sass – loader > CSS – loader > MiniCssExtractPlugin. Loader

The rule is: from bottom to top, right to left

The complete code

directory

index.js

import '.. /css/index.css'
import '.. /scss/index.scss'

console.log('This is an entry file.')
console.log('Environment variables:', process.env.NODE_ENV)
Copy the code

webpack.config.js

const path = require('path')

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

console.log('Environment variables:', process.env.NODE_ENV)

module.exports = {
  // entry: path.resolve(__dirname, '.. /src/js/index.js'),
  entry: {
    main: path.resolve(__dirname, '.. /src/js/index.js'),
    header: path.resolve(__dirname, '.. /src/js/header.js'),
    footer: path.resolve(__dirname, '.. /src/js/footer.js'),},output: {
    // filename: 'main.js',
    filename: 'js/[name].[fullhash].js'.path: path.resolve(__dirname, '.. /dist')},// devServer: {
  // port: 3000,
  // hot: true,
  // contentBase: '.. /dist'
  // },
  plugins: [
    // new HtmlWebpackPlugin({
    //   title: '首页'
    // }),
    // Configure multiple htmlWebPackPlugins for as many pages as possible
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, '.. /src/html/index.html'),
      filename: 'index.html'.chunks: ['main'] // The module name corresponding to the entry file (entry configuration), which can be understood here as importing main.js
    }),
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, '.. /src/html/header.html'),
      filename: 'header.html'.chunks: ['header']}),new HtmlWebpackPlugin({
      template: path.resolve(__dirname, '.. /src/html/footer.html'),
      filename: 'footer.html'.chunks: ['footer']}),new CleanWebpackPlugin(),
    new MiniCssExtractPlugin({
      filename: 'css/[name].[fullhash].css'})].module: {
    rules: [{test: /\.css$/i,
        use: [
          //'style-loader', 'css-loader'
          MiniCssExtractPlugin.loader, 'css-loader'] {},test: /\.s[ac]ss$/i,
        use: [
          MiniCssExtractPlugin.loader, 'css-loader'.'sass-loader'[}]}Copy the code

webpack.prod.js

const { merge } = require('webpack-merge')
const common = require('./webpack.config.js')
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin')

module.exports = merge(common, {
  mode: 'production'.optimization: {
    minimizer: [
      // In webpack@5, you can use '... 'syntax to extend the existing minimizer (that is,' terser-webpack-plugin ') by uncommenting the next line
      `... `.new CssMinimizerPlugin(),
    ],
  },
})
Copy the code

series

Using WebPack5 (0) : Concepts Using WebPack5 (1) : Starting Using WebPack5 (2) : Configuring Multiple environments Using WebPack5 (3) : Loading the CSS Using WebPack5 (4) : Load resource file Webpack5 use (5) : Babel translation JS code use (6) : optimization