Webpack 2+: How to apply different loaders for files with same extension?

前端 未结 3 1451
青春惊慌失措
青春惊慌失措 2020-12-10 04:10

Here\'s my use-case: Most svgs should be inlined. So I setup a rule like this:

{test: /\\.svg$/, use: \"svg-inline-loader\"},

In some insta

相关标签:
3条回答
  • 2020-12-10 04:48

    In addition to test, you can specify include/exclude conditions. From the docs on configuration options:

    {
        test: /\.jsx?$/,
        include: [
          path.resolve(__dirname, "app")
        ],
        exclude: [
          path.resolve(__dirname, "app/demo-files")
        ]
        // these are matching conditions, each accepting a regular expression or string
        // test and include have the same behavior, both must be matched
        // exclude must not be matched (takes preferrence over test and include)
        // Best practices:
        // - Use RegExp only in test and for filename matching
        // - Use arrays of absolute paths in include and exclude
        // - Try to avoid exclude and prefer include
    }
    
    0 讨论(0)
  • 2020-12-10 04:49

    So I recently attended a talk by webpack's Juho Vepsäläinen and found the answer in this slide:

    {
      test: /.css$/,
    
      oneOf: [
        {
          resourceQuery: /inline/, // foo.css?inline
          use: 'url-loader',
        },
        {
          resourceQuery: /external/, // foo.css?external
          use: 'file-loader',
        },
      ],
    }
    

    resourceQuery to the rescue!

    0 讨论(0)
  • 2020-12-10 04:52

    resolveLoader.alias will be solution for you.

    Your config will look like this:

    resolveLoader: {
      alias: {
        myLoader1: "svg-inline-loader", // and much more
        myLoader2: "file-loader!image-webpack-loader" // and much more
      }
    }
    

    and usage:

    require('myLoader1!path/to/file1.svg');
    require('myLoader2!path/to/file2.svg');
    

    Or if you want for example myLoader1 config to be default and from time to time use myLoader2 loaders use this kind of config:

    {
      test: /\.svg$/,
      use: "svg-inline-loader" // and much more
    }
    
    // ...
    
    resolveLoader: {
      alias: {
        myLoader: "file-loader!image-webpack-loader" // and much more
      }
    }
    

    and use like this:

    require('path/to/file1.svg'); // default svg-inline-loader
    require('!myLoader!path/to/file2.svg'); // specific file-loader!image-webpack-loader
    // ! at the beginning - disables loaders from default
    // and myLoader enables file-loader and image-webpack-loader
    

    PS. I had similar question here it's for webpack 1 but documentation says that resolveLoader.alias works the same.

    0 讨论(0)
提交回复
热议问题