1. Inline CSS with style-loader and css-loader

The simplest way to have webpack support CSS in your project is to require the CSS file from your javascript entry file. Webpack will then inline these CSS rules into a <style> tag in the html document.

To do this, we first need to install the css-loader and style-loader packages:

npm install --save css-loader style-loader

In your webpack configuration, note the module section:

// app.js
var webpack = require('webpack');
var path = require('path');

module.exports = {
  output: {
    path: path.join(__dirname, 'build'),
    filename: '[name].js'
  },

  entry: {
    app: './js/app.js'
  },

  module: {
    loaders: [
      {test: /\.css$/, loader: 'style-loader!css-loader'}
    ]
  }
}

Here we're using one loader to be applied to files ending in .css. We've used the webpack string loader chaining syntax here, though, we easily could have representated that configuration as an array, like this:

{test: /\.css$/, loaders: ["style-loader", "css-loader"]}

In the string syntax, the ! acts as the separator between different loaders. I wanted to point out both syntax's here, because you're likely to see both forms scattered in configuration files.


A Very Important Detail About Loaders

When multiple loaders are chained like this, they are applied right to left.

That means the file is first passed to right-most loader, and the output of that is passed to the loader to the left, and so on.


Deconstructing the style and css loaders

Let's break down what this loader configuration is doing.

When webpack encounters a CSS file, it passes it first to the css loader. The css-loader, among other things, translates certain CSS nuances like @import and url statements into webpack require statements. This is helpful so that external resources that we make use of in CSS (like background images) stay within the webpack universe (this will become extremely important for production configurations).

Next, the translated CSS is passed on to the style loader which takes the CSS and inserts it into a style tag, which is inserted into the <head> of the document that loads the javascript file.

Create a simple HTML document to load in your app.js file. Save it at the root of your project.

<!DOCTYPE html>
<html>
  <head>
    <title>Test</title>
    <script type="text/javascript" src="./build/app.js"></script>
  </head>
  <body>
    <div class="banner">

    </div>
  </body>
</html>

Open this file in your browser: open index.html

Then, use your browser's "view source", and you'll see the <style> tag in your document's <head> tag.

results matching ""

    No results matching ""