webpackwebpack-loader

How to import all files except JS, CSS, HTML as assets in Webpack?


I know that I can import assets (e.g. images) in my JS code using Webpack. This is useful to include hash of the file in it's name, so I can cache the assets forever using HTTP

import cat from './cat.png'

export function CatGallery() {
    return <img src={cat} alt="A wonderful cat" />
}
//webpack.config.js
module.exports = {
  output: {
      assetModuleFilename: '[name].[contenthash][ext]',
  },

  module: 
      rules: [
        {
          test: /\.png$/,
          type: 'asset/resource'
        },
      ],
  }
};

What is unfortunate is that I have to explicitly list every extension my assets can have in test regex. Is there a way to write a regex that will cover all files except ones related to CSS, JS and HTML?


Solution

  • You can modify your configuration using a regex that matches the ones except listed in the group. This regex uses a construct called negative lookahead - (?!a)

    //webpack.config.js
    module.exports = {
      output: {
          assetModuleFilename: '[name].[contenthash][ext]',
      },
    
      module: 
          rules: [
            {
              test: /\.(?!(css|html|js|ts|jsx|tsx)$)[^.]+$/,
              type: 'asset/resource'
            },
          ],
      }
    };
    

    Explanation:

    /
    \. # match dot (escaped)
    (?! # not followed by
        (css|html|js|ts|jsx|tsx) # any of these extensions
        $ # that are in the end. Prevents false matches like .ts.png 
    )
    [^.]+$ # the previous group didn't consume any input - we're still in place after dot. 
    # The extension itself doesn't contain dots and must be at least one character, 
    # and also should be the last in the filename
    /