47

I am upgrading my current project to Webpack2, which it was using Webpack1 prior. I have looked into a couple tutorials about upgrading and in general, I do understand.

The issue I keep running into, though, is I'm not sure when to use 'use' and 'loader' in when specifying the module rules (loaders). At first, I thought use replaced loader. I understand this type of syntax:

module: {
  rules: [{
    test: /\.scss$/,
    use: [
      {
        loader: 'postcss-loader',
        options: {
          plugins: ...
        }
      },
      'sass-loader'
    ]
  }]
}

However, when I use the ExtractTextPlugin it doesn't seem to like when it's consdiered a use. I've tried this:

      {
        test: /\.scss$/,
        use: [
          {
            loader: ExtractTextPlugin.extract({
              fallbackLoader: 'style-loader',
              loader: scssLoaders
            })
          }]
      },

with the scssLoaders being:

var scssLoaders = [
  {
    loader: 'css-loader',
    options: {
      modules: true,
      importLoaders: '2',
      localIdentName: '[name]__[local]__[hash:base64:5]'
    }
  },
  {
    loader: 'postcss-loader'
  },
  {
    loader: 'sass-loader',
    options: {
      outputStyle: 'expanded',
      sourceMap: true,
      sourceMapContents: true
    }
  }
];

I'll just stop here before I go off about other problems. Can someone please help explain what I am missing here? Feel free to ask for any other code you need to help!

Thank you in advance.

Sunil Garg
  • 14,608
  • 25
  • 132
  • 189
TwistedSt
  • 632
  • 1
  • 6
  • 14

2 Answers2

57

As the Webpack 2 migration tutorial states, the difference between both is, that if when we want an array of loaders, we have to use use, if it's just one loader, then we have to use loader:

module: {
   rules: [
      {
        test: /\.jsx$/,
        loader: "babel-loader", // Do not use "use" here
        options: {
          // ...
        }
      },
      {
        test: /\.less$/,
        loader: "style-loader!css-loader!less-loader"
        use: [
          "style-loader",
          "css-loader",
          "less-loader"
        ]
      }
    ]
  }
ultranaut
  • 2,132
  • 1
  • 17
  • 22
Albert Olivé Corbella
  • 4,061
  • 7
  • 48
  • 66
  • 5
    Note: That using `loaders` as opposed to `loader` will still work but is now considered a legacy option https://webpack.js.org/guides/migrating/#chaining-loaders – Simon_Weaver Jun 25 '17 at 21:59
  • 7
    Great answer, thanks. You have to love it when a tool already criticized for its complex configuration decides to make it even *harder* to configure by making you use two properties when you used to just be able to use one :( – machineghost Jul 13 '18 at 22:12
15

module.rules is meant for loaders. Specifying a rule as loader is just a shortcut for

use: [{loader}]

For plugins, use the plugins property in your configuration.

Sunil Garg
  • 14,608
  • 25
  • 132
  • 189
simon04
  • 3,054
  • 29
  • 25