Movatterモバイル変換


[0]ホーム

URL:


webpack logo
ag grid
ag charts

Plugins

Plugins are thebackbone of webpack. Webpack itself is built on thesame plugin system that you use in your webpack configuration!

They also serve the purpose of doinganything else that aloader cannot do. Webpack providesmany such plugins out of the box.

tip

When consumingwebpack-sources package in plugins, userequire('webpack').sources instead ofrequire('webpack-sources') to avoid version conflicts for persistent caching.

Anatomy

A webpackplugin is a JavaScript object that has anapply method. Thisapply method is called by the webpack compiler, giving access to theentire compilation lifecycle.

ConsoleLogOnBuildWebpackPlugin.js

const pluginName='ConsoleLogOnBuildWebpackPlugin';classConsoleLogOnBuildWebpackPlugin{apply(compiler){    compiler.hooks.run.tap(pluginName,(compilation)=>{      console.log('The webpack build process is starting!');});}}module.exports= ConsoleLogOnBuildWebpackPlugin;

It is recommended that the first parameter of the tap method of the compiler hook should be a camelized version of the plugin name. It is advisable to use a constant for this so it can be reused in all hooks.

Usage

Sinceplugins can take arguments/options, you must pass anew instance to theplugins property in your webpack configuration.

Depending on how you are using webpack, there are multiple ways to use plugins.

Configuration

webpack.config.js

const HtmlWebpackPlugin=require('html-webpack-plugin');const webpack=require('webpack');//to access built-in pluginsconst 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:[newwebpack.ProgressPlugin(),newHtmlWebpackPlugin({ template:'./src/index.html'}),],};

TheProgressPlugin is used to customize how progress should be reported during compilation, andHtmlWebpackPlugin will generate a HTML file including themy-first-webpack.bundle.js file using ascript tag.

Node API

When using the Node API, you can also pass plugins via theplugins property in the configuration.

some-node-script.js

const webpack=require('webpack');//to access webpack runtimeconst configuration=require('./webpack.config.js');let compiler=webpack(configuration);newwebpack.ProgressPlugin().apply(compiler);compiler.run(function(err, stats){// ...});
tip

Did you know: The example seen above is extremely similar to thewebpack runtime itself! There are lots of great usage examples hiding in thewebpack source code that you can apply to your own configurations and scripts!

« Previous
Loaders

7 Contributors

TheLarkInnjhnnsrouzbeh84johnstewMisterDevbyzykchenxsan

[8]ページ先頭

©2009-2025 Movatter.jp