Webpack 4 plugins

Time:2019-9-9

Demo code point here, space is limited, only a few commonly used.

start


What is plugins?

While loaders are used to transform certain types of modules, plugins can be leveraged to perform a wider range of tasks like bundle optimization, asset management and injection of environment variables.

Plugins can be used to perform a wider range of tasks, such as packaging optimization, resource management, and redefining variables in the environment.

HtmlWebpackPlugin


This plug-in will generate an HTML5 file for you and help you to import web packaged JS and other files.

Installation:

npm i -D html-webpack-plugin

Configure in webpack. config. js:

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

module.exports = {
  // mode: 'production',
  mode: 'development',
  // Entrance
  // entry: './src/index.js',
  entry: {
    main: './src/index.js',
  },
  module: {...},
+  plugins: [
+    new HtmlWebpackPlugin({
+ title:'webpack 4 plugins',
+      template: './src/index.html'
+    }),
+  ],
  // Export
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
}

Then create index. HTML as a template under the SRC directory:

CleanWebpackPlugin


The webpack plug-in used to delete/clear the build folder is actually to empty the dist folder before packaging.

Still installed:

npm i -D clean-webpack-plugin

Then configure:

// webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
+ const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = {
  mode: 'development',
  entry: {
    main: './src/index.js',
  },
  module: {...},
  plugins: [
    new HtmlWebpackPlugin({
      Title:'webpack 4 plugins',
      template: './src/index.html'
    }),
+    new CleanWebpackPlugin(),
  ],
  // Export
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
}

HotModuleReplacementPlugin


Module hot replacement plug-ins, namely HMR, webpack4 with plug-ins, without installation, cooperate in developer modedevServerUse.

Note: Never enable HMR in a production environment

Install webpack-dev-server:

npm i -D webpack-dev-server

To configure:

// webpack.config.js

...
+ const webpack = require('webpack');

module.exports = {
  mode: 'development',
  entry: {
    main: './src/index.js',
  },
  module: {...},
  plugins: [
    new HtmlWebpackPlugin({
      Title:'webpack 4 plugins',
      template: './src/index.html'
    }),
    new CleanWebpackPlugin(),
+   new webpack.HotModuleReplacementPlugin(),
  ],
+  devServer: {
+    contentBase: path.resolve(__dirname, "dist"),
+// Enable gzip
+    compress: true,
+        open: true,
+    port: 9000,
+    hot: true,
+    hotOnly: true,
+  },
  // Export
  output: {...},
}

Then configure commands in script in package. josn, which is convenient and practical.

// package.json
...
"scripts": {
+ "start": "webpack-dev-server",
  "bundle": "webpack"
},
...

Then run the command:

npm start

Then change index. less, cut back to the browser, and you will find that the CSS effect has changed.

You can try to modify the JS module to see the effect, modify index. js:

// index.js
// Add this code at the end

...
+ if (module.hot) {
+   module.hot.accept('./components/Header', () => {
+     Header();
+   })
+ }

Then restart webpack-dev-server and modify Header.js:

// Header.js

...
Header. innerText = modified header';
...

Cut back to the browser and you’ll find a modified header.

miniCssExtractPlugin


Mini-css-extract-plugin extracts CSS into a separate file. Similar functions include extract-text-webpack-plugin (obsolete). Compared with mini-css-extract-plugin, the advantages of mini-css-extract-plugin are as follows:

  • Asynchronous loading
  • No duplicate compilation (performance)
  • Easy to use
  • CSS-specific

Installation:

npm i -D mini-css-extract-plugin

Then configure:

// webpack.config.js

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

module.exports = {
  mode: 'development',
  entry: {...},
  module: {
    rules: [
    ...
    {
      // Packing css, less
      test: /\.(css|less)$/,
      use: [
        // It must be added here.
 +       {
 +         loader: MiniCssExtractPlugin.loader,
 +       },
        {
          loader: 'css-loader',
          options: {
            importLoaders: 2,
          }
        },
        'less-loader',
        'postcss-loader',
      ],
    }],
  },
  plugins: [
    ...
+    new MiniCssExtractPlugin({
+      filename: 'css/[name].css',
+     chunkFilename: 'css/[id].css',
+    }),
  ],
  devServer: {...},
  // Export
  output: {...},
}

Then executenpm run bundlePack, and you’ll find that the CSS is packed.

PurgecssPlugin


The unused CSS can be removed, which is usually used in conjunction with glob and glob-all.

Installation:

npm i -D purgecss-webpack-plugin glob

To configure:

// webpack.config.js

...
+ const glob = require('glob');
+ const PurgecssPlugin = require('purgecss-webpack-plugin');

module.exports = {
  mode: 'development',
  entry: {...},
  module: {...},
  plugins: [
    ...
+    new PurgecssPlugin({
+      paths: glob.sync(`${path.join(__dirname, 'src')}/**/*`, 
+      { 
+// Not matching directories, only matching files
+        nodir: true,
+      }),
+    }),
  ],
  devServer: {...},
  // Export
  output: {...},
}

optimizeCssAssetsWebpackPlugin


When packaged under production, JS files are automatically compressed, but CSS does not, so optimize-css-assets-webpack-plugin is used to compress css.

Installation:

npm i -D optimize-css-assets-webpack-plugin

To configure:

// webpack.config.js

...
+ const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');

module.exports = {
  mode: 'development',
  entry: {...},
  module: {...},
  plugins: [
    ...
+   new OptimizeCssAssetsPlugin(),
  ],
  devServer: {...},
  // Export
  output: {...},
}

After packaging, you will find that all the CSS files are compressed.

Remarks


The space is limited, so there aren’t many bbs.

Recommended Today

Notes on tensorflow 2 deep learning (I) tensorflow Foundation

This series of notes records the process of learning tensorflow2, mainly based on https://github.com/dragen1860/Deep-Learning-with-TensorFlow-book Learning First of all, it needs to be clear that tensorflow is a scientific computing library for deep learning algorithm, and the internal data is stored in theTensor objectAll operations (OPS) are also based on tensor objects. data type Fundamentals in […]