What's a Webpack Loader, Really?

Loaders are the basic building blocks of Webpack. These are the rules we apply to various files in order to transform their contents to something that we can include in our final bundle.

But here's the weird thing about loaders. They only deal in JavaScript.

That's right. You can apply loaders to images, CSS, SASS, markdown and all kinds of other file types, but under the hood, they're all getting converted to JavaScript. You can go read the docs for writing custom loaders, and you'll see that a loader is nothing more than a function that accepts some source code and returns JavaScript.

So what gives? When I write a loader rule like this, for including CSS into my bundle, does that mean it's all still JavaScript?


module.exports = {  
  module: {
    rules: [
      {
        test: /\.css$/,
        // don't worry about why we need two loaders for right now
        use: [ 'style-loader', 'css-loader' ]
      }
    ]  
  }
}

It sure does. The key to remember here is that loaders are rules for how to include assets in your bundle. I mentioned a couple days ago that bundles are just JavaScript files. What this rule says is that any time your dependency graph points to a css file, (ie. import "./some/file.css"), Webpack will parse that CSS and add logic into your final bundle that injects that CSS into the DOM at runtime.

As written here, your final build would have no CSS files, no style tags, and no link tags in your HTML. The JavaScript bundle will take care of injecting your CSS (by default as a style tag) when the user loads the page. Sometimes this is what you want. For instance, it's really great to be able to import styles specific to a component that you're building.

But sometimes you just want a static CSS file with a plain old link tag that references it. How do we get that? Monday, we'll talk about plugins.

Enjoy your weekend!


Did you like this?

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

Icon