Your First Loaders

In this article we’re going to keep looking into how webpack loads files, specifically style sheets. We’ll introduce the concept of loaders and how webpack uses them to handle various file types. We’re going to start right where we left off.

If you need to catch up:

git clone https://github.com/lawwantsin/webpack-course.git
cd webpack-course
git checkout loaders1
npm install

Okay, back in the terminal we’re going to create a new file src/main.css.

touch src/main.css

Let’s add something simple.

body {
  color: red;
}

In our main.js, let’s require("./main.css") in main.js. In the terminal, you see the dev server reload and throw an error.

So what this error is saying is Webpack doesn’t know every language, it just knows javascript. It relies on an ecosystem of loaders to handle other types of files. There is a loader for images, and one for markdown and fonts and svg, really everything you can imagine.

We’ll get deep into loaders soon. For now, let’s add 2 loader packages via the terminal to get this css working.

npm install style-loader css-loader

In your webpack.dev.js, you’re going to add a modules object that has a rules array right below the devServer object.

  devServer: {...},
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [{ loader: "style-loader" },
              { loader: "css-loader" }]
      }
    ]
  }

Rules will hold all of our loader config objects. The property test takes a regular expression that tells webpack when you see dot css, use the following loaders. In this case, css-loader lints the main.css before passing it to the style-loaders which for it's part includes a bit of javascript that will dynamically add a style tag to the head of our document and print the css inside on page load. That's what the style loader does under the covers.

We return to our browser and we have color.

We can add some stuff, make this hello world a little prettier. If you're following along, press save after everything line.

body {
  margin: 0;
  background-color: #444;
}

h1 {
  display: flex;
  -ms-align-items: center;
  align-items: center;
  justify-content: center;
  font-size: 5em;
  font-family: sans-serif;
  color: white;
  text-shadow: 0 0 20px black;
  height: 100vh;
}

And the browser keeps reloading on the fly as I save the file.

In Sum

In this article we learned how to add a css loader to get styles auto-reloading in the browser. We then tested a bit of the css linting Webpack gives us.

git checkout loaders1-final

Next Up

What’s even better is surfacing errors right in the browser. As well as more loaders for images and html.