A modern boilerplate for writing Webpack plugins
MIT License
Why use this boilerplate? It comes with a lot of features out of the box that will let you focus on writing webpack plugins.
This example code is already written in
src/index.js
. To see the demo plugin in action, you shouldn't need to write any new code. This is just a walkthrough of how it was written.
Let's say you want to create a webpack plugin called DemoPlugin
that prints "Hello World" once webpack compilation is done (super useful!).
To do this, we will need to make sure our code fulfills a few important properties:
DemoPlugin
.apply
that takes a compiler
parameter. This compiler parameter is described in more details in the compiler hook documentation.console.log
.Your plugin's main file will be the src/index.js
file. It should look something like this:
export default class DemoPlugin {
constructor(options) {
this.options = options;
}
apply(compiler) {
compiler.hooks.done.tap('DemoPlugin', () => {
console.log('\nHello world\n');
});
}
}
Notice we have used compiler.hooks.done.tap
to tap into the done
lifecycle hook. Our callback will now be called when webpack compilation step has been completed.
Now we need to compile our plugin.
npm run build
We now have our built plugin files in the /dist
directory. The main one we want to import is located in dist/cjs.js
. When you publish your NPM module, this will be the file that gets imported since it's specified in our package.json
file as our main
file.
For local development, you'll have to directly import the
cjs.js
to test your local changes.
Now, inside of your webpack configuration for your project, you can import and add your plugin to your plugins list.
const DemoPlugin = require('./path/to/DemoPlugin/dist/cjs');
module.exports = {
mode: 'development',
plugins: [
new DemoPlugin({}),
],
};
The final step is to build your webpack project. In the output, you should see that the DemoPlugin
was called after webpack finished compilation and printed "Hello World" to the console.
And that's it! You now can work on adding some useful functionality to your plugin.
Important: Don't forget to rebuild your plugin each time you make a change!
See the webpack plugin API Docs for a full description of webpack plugin API.
Clone the repository into your "DemoPlugin" directory (replace DemoPlugin with your plugin name).
git clone https://github.com/ctaylo21/webpack-plugin-boilerplate.git DemoPlugin && cd DemoPlugin
Remove the git repository, and then initialize a new one
rm -rf .git && git init
Remove README and replace with your own
rm README.md && touch README.md
Update package.json
and install dependencies
npm init && npm install
Don't forget to update any relevant fields in the package.json
file!
Start coding!
If you find any problems or bugs, please open a new issue.