Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”
This article also participated in the “Digitalstar Project” to win a creative gift package and creative incentive money
preface
After the previous article “Loader practice how to implement a Loader by hand”, to extend loader.
Plugin is a pillar feature of WebPack. Webpack itself is built on top of the same plugin system you use in your WebPack configuration!
Plug-ins are designed to solve other things that loader cannot implement.
usage
Since plug-ins can carry parameters/options, you must pass a new instance to the plugins property in the WebPack configuration.
Depending on your WebPack usage, there should be several ways to use the plug-in.
Analyze the
The Webpack plug-in is a JavaScript object with the Apply method. The Apply method is called by the Webpack Compiler and the Compiler object is accessible throughout the compile life cycle.
ConsoleLogOnBuildWebpackPlugin.js
const pluginName = 'ConsoleLogOnBuildWebpackPlugin';
class ConsoleLogOnBuildWebpackPlugin {
apply(compiler) {
compiler.hooks.run.tap(pluginName, (compilation) = > {
console.log('Webpack build process begins! '); }); }}module.exports = ConsoleLogOnBuildWebpackPlugin;
Copy the code
The first argument to compiler Hook’s tap method should be the camel-named plug-in name. It is recommended to use a constant for this so that it can be reused in all hooks.
Configuration mode
webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin'); // Install via NPM
const webpack = require('webpack'); // Access the built-in plug-in
const path = require('path');
module.exports = {
entry: './path/to/my/entry/file.js'.output: {
filename: 'my-first-webpack.bundle.js'.path: path.resolve(__dirname, 'dist'),},module: {
rules: [{test: /.(js|jsx)$/,
use: 'babel-loader',}]},plugins: [
new webpack.ProgressPlugin(),
new HtmlWebpackPlugin({ template: './src/index.html'})]};Copy the code
ProgressPlugin is used to customize progress reports during compilation. HtmlWebpackPlugin will generate an HTML file and use script to introduce a JS file named my-first-webpack.bundle.js.
other
Reference links: webpack.docschina.org/concepts/pl…