Skip to content

Latest commit

 

History

History

example4

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 

Earlier in the tutorial I mentioned loaders. These will help us require non-js files in our code. In this case, the only loader we will need is the css loader. First we need to install the loader:

npm install --save-dev style-loader css-loader

Now that it's installed we can tweak our config to include the css loader:

// webpack.config.js
var path = require('path')
var webpack = require('webpack')

module.exports = {
  entry: ['./src/index'],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin({
      compressor: {
        warnings: false,
      },
    }),
    new webpack.optimize.OccurenceOrderPlugin()
  ],
  module: {
    loaders: [{
      test: /\.css$/,
      loaders: ['style', 'css']
    }]
  }
}

Going over the new properties one by one:

  • module - Options affecting your files
    • loaders - An array of loaders that we specify for our application
      • test - A regular expression to match the loader with a file
      • loaders - Which loaders to use for files that match the test

This time when you run webpack, if we require a file that ends in .css, then we will apply the style and css loaders to it, which adds the CSS to the bundle.

If we didn't have the loaders, then we would get an error like this:

ERROR in ./test.css
Module parse failed: /Users/Developer/workspace/tutorials/webpack/part1/example1/test.css
Line 1: Unexpected token {
You may need an appropriate loader to handle this file type.

Optional

If you want to use SCSS instead of CSS you would need to run:

npm install --save-dev sass-loader node-sass webpack

and instead your loader would be written as

{
  test: /\.scss$/,
  loaders: ["style", "css", "sass"]
}

The process is similar for LESS.

An important aspect to recognize is that there is an order to which these loaders need to be specified. In the above example, the sass loader is first applied to your .scss files, then the css loader, and finally the style loader. As you can see, the pattern is that these loaders are applied from right to left.