What's a Webpack Plugin?

On Friday, I discussed how Webpack loaders are just functions that produce JavaScript. Loaders allow us to do things like import CSS directly into our JavaScript files, which then inject those styles into the DOM at runtime. I left you with a question: What to do if you want to produce a CSS file in your output directory and link to it with a <link> tag from your html file?

This is where plugins come in. While loaders can only transform the JavaScript that is included in your final bundle (remember, a bundle refers to a generated JavaScript file, not to the output directory as a whole), plugins have access to the whole build process and can work outside of the JS dependency graph. This means plugins can do everything from modifying how build progress is reported on the command line to creating in-memory dev servers that serve and reload your code as you work.

To create a CSS file and link to it in our HTML, we need a plugin. But we still need a loader to generate the CSS itself from the source files as specified by our import statements. Our tool of choice will be the MiniCssExtractPlugin, which is itself a plugin, but also provides a loader. Our final config looks something like this:


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

module.exports = {

  module: {
    rules: [
      {
        // apply this rule to modules that end in .css
        test: /\.css$/i,

        // loaders are applied right-to-left, so we first apply
        // the css-loader, which passes the extracted css to a loader provided
        // by the MiniCssExtractPlugin class
        use: [MiniCssExtractPlugin.loader, 'css-loader'],
      }
    ]
  },
  plugins: [
    // providing an instance of MiniCssExtractPlugin in our plugins array
    // takes the CSS that is generated in our loader above, puts it into  
    // its own css file in the output directory, and updates our html file
    // with a link tag that points to the generated CSS file
    new MiniCssExtractPlugin()
  ]
}

The loader and plugin work together. The loader parses our import statements and figure out what the final CSS should include. The plugin takes care of everything outside of the generated JavaScript file, which is to say creating the CSS file and updating our HTML.

Neat, huh?

More tomorrow.


Did you like this?

I send a daily email with tips and ideas like this one. Join the party!

Icon