Alex Antonov
Alex Antonov

Reputation: 15156

How to define precendence of loaders in webpack?

I use webpack to build a server build, the config looks like:

loaders: [
  {
    test: /\.js$/,
    exclude: [/node_modules/],
    loader: "babel-loader",
    query: {
      presets: ["es2015", "react"],
      plugins: ["transform-object-rest-spread"]
    }
  }, {
    test: new RegExp(`/
      stardust
      |redux-form
      |axios
      |shuffle
    `),
    loader: "null-loader"
  }
]

Idea is pretty simple: if something matches regexp in the second loader, it shouldn't be loaded. It works well until I'm loading this:

import shuffle     from "shufflejs/dist/shuffle.min.js"

It matches to both loaders and loaded to the bundle. How can I make null-loader precedence higher than the babel?

Upvotes: 1

Views: 133

Answers (1)

Fadi Hania
Fadi Hania

Reputation: 723

You can use pre-loaders as described in webpack documentation basically you will use your regex with null-loader as a pre-loader this way it will be resolved before your loaders. So, if regex matches null-loader will be used and it won't load the module.

Here's the modified code:

preLoaders: [
    {
        test: new RegExp(`/
            stardust
            |redux-form
            |axios
            |shuffle
        `),
        loader: "null-loader"
    }
],
loaders: [
    {
        test: /\.js$/,
        exclude: [/node_modules/],
        loader: "babel-loader",
        query: {
            presets: ["es2015", "react"],
            plugins: ["transform-object-rest-spread"]
        }
    }
]

The only other solution I can think of is to rely on regular expressions to exclude files containing these word. I'm not an expert in Regex but I'll try to suggest an expression:

loaders: [
    {
        test: /^(?!stardust|redux-form|axios|shuffle)([a-zA-Z]+)\.js$/,
        exclude: [/node_modules/],
        loader: "babel-loader",
        query: {
            presets: ["es2015", "react"],
            plugins: ["transform-object-rest-spread"]
        }
    }
]

Upvotes: 1

Related Questions