Kent Wood
Kent Wood

Reputation: 1522

How to configure a loader for a specific path in webpack

In webpack the Rule.test option only checks a file's name, not its full path. I have files of the same type in multiple directories and want to apply different loaders based on a file's path, e.g.

{
    test: /aaa\/.*.html/,
    loader: 'loaderA'
},
{
    test: /bbb\/.*.html/,
    loader: 'loaderB'
}

Is there any way to make that work?

Upvotes: 39

Views: 34878

Answers (2)

Qwerty
Qwerty

Reputation: 32028

Another solution would be to use those regexes in the include / exclude field.

{
    test: /\.html$/,
    include: /aaa\/.*.html/,
    loader: 'loaderA'
},
{
    test: /\.html$/,
    include: /bbb\/.*.html/,
    loader: 'loaderB'
}

Or using this pattern (useful for combining tailwind with other css processors)

{
  test: /src\\index.css$/,  // <- note: windows
  // ...
},
{
  test: /\.css$/,
  exclude: /src\\index.css$/,
  // ...
}

Upvotes: 1

Bob  Sponge
Bob Sponge

Reputation: 4738

You can use include and exclude properties (docs):

{
    test:/\.html$/,
    include: [
        path.resolve(__dirname, "app/pathA")
    ],
    loader: 'loaderA'
},
{
    test:/\.html$/,
    include: [
        path.resolve(__dirname, "app/pathB")
    ],
    loader: 'loaderB'
}

For files in folder pathA will applied loader loaderA, and for pathB - loader loaderB.

Upvotes: 78

Related Questions