Search code examples
webpackwebpack-config

What are the differences between `test`, `include`, `resource` attributes in webpack modules rules configuration?


In webpack.config.js to determine module we can use 3 different attributes:

...
module:{
    rules: [
        {
            test: ... // the first one, commonly used in most example we can found on internet
            include: ... // the second one
            resource: ... // the third one
            use: ['style-loader','css-loader'],
        },
        ...
    ],  
    ...
}

Docs are not explanatory about them:

Rule.test
Include all modules that pass test assertion. If you supply a Rule.test option, you cannot also supply a Rule.resource. See Rule.resource and Condition.test for details.

Rule.include
Include all modules matching any of these conditions. If you supply a Rule.include option, you cannot also supply a Rule.resource. See Rule.resource and Condition.include for details.

Rule.resource
A Condition matched with the resource. See details in Rule conditions.

Each of them are Condition type. Some of them are mutually exclusive. But what is the purpose of each? When we should use each?

If there will be only test everything would be clear.


Solution

  • I'm not familiar with the complete history of Webpack, but I believe Rule.resource is a legacy option that is being phased out, since almost no one is using it.

    With Rule.resource you can have sub-conditions, which would otherwise be complicated to write using a single RegExp:

    {
      resource: {
        and: [
          /\.js$/,
          /src\/directory/,
        ],
        not: /node_modules/
      }
    }
    

    That looks a lot like how you would use the Rule.test, Rule.include, and Rule.exclude options, which used to be called shortcut options, but they are now the main ones.

    Nowadays the way you are meant to use them is to match the file extension with Rule.test and if you need to list specific directories or specific files you should use Rule.include or Rule.exclude.

    This convention makes config easy to read and easy to reuse across projects.

    Rule.test and Rule.include actually work the same way, you could even merge them into a single condition, but at that point you might as well go back to Rule.resource.

    Currently Rule.resource works the same as Rule.test, so there is no point in using both, that is probably why they are mutually exclusive.