Original translation, please indicate the source when reprinting.
Original address: https://webpack.js.org/concepts/plugins/
Plugins are the heart of webpack . Webpack itself is built using the same plugin system used in your wepback configuration file.
It can also do anything else that a loader can't.
Parse
A webpack plugin is a javascript object with an apply attribute . The apply property is called by the webpack compiler and has this right for the entire compilation lifecycle.
ConsoleLogOnBuildWebpackPlugin.js
functionConsoleLogOnBuildWebpackPlugin(){ }; ConsoleLogOnBuildWebpackPlugin.prototype.apply =function(compiler){ compiler.plugin('run',function(compiler, callback){ console.log("The webpack build process is starting!!!"); callback(); }); };
usage
Because plugins can take parameters or options, you must generate a new instance in the plugins property of your configuration file.
There are different ways to use plugins depending on how you use webpack .
configure
webpack.config.js
const HtmlWebpackPlugin =require('html-webpack-plugin');//installed via npm const webpack =require('webpack');//to access built-in plugins const path =require('path'); const config ={ entry:'./path/to/my/entry/file.js', output:{ filename:'my-first-webpack.bundle.js', path: path.resolve(__dirname,'dist') }, module:{ rules:[ { test:/\.(js|jsx)$/, loader:'babel-loader' } ] }, plugins:[ newwebpack.optimize.UglifyJsPlugin(), newHtmlWebpackPlugin({template:'./src/index.html'}) ] }; module.exports = config;
Node API
some-node-script.js
const webpack =require('webpack');//to access webpack runtime const configuration =require('./webpack.config.js'); let compiler =webpack(configuration); compiler.apply(newwebpack.ProgressPlugin()); compiler.run(function(err, stats){ // ... });
-- End --