Use the webpack asset module with a custom output filename

Viewed 6025

Suppose I had the following webpack.config.js file:

module.exports = {
    //...
    output: {
        filename: "[name].bundle.js",
        path: path.resolve(__dirname, "dist"),
        assetModuleFilename: "assets/[name][ext]",
    },
    module: {
        rules: [
            {
                test: /\.(woff|woff2|eot|ttf|otf)$/i,
                type: "asset/resource",
            },
            {
                test: /\.(png|svg|jpg|jpeg|gif)$/i,
                type: 'asset/resource',
            },
        ],
    },
    plugins: [
    //...
    ],
};

My question is how can I separate the fonts from the images? I want to put each one in a subdirectory called "fonts" and "images" under the assets folder. I know this is possible using the "file-loader". However, I want to use the asset module.

2 Answers

You can use the Rule.generator.filename property:

module.exports = {
  // ...

  module : {
    rules : [
      // ...

      // Fonts
      {
        test      : /\.(woff2?|ttf|eot)(\?v=\w+)?$/,
        type      : 'asset/resource',
        generator : {
          filename : 'fonts/[name][ext][query]',
        }
      },
    ]
  },

  // ...
}

This should be OK.

      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 8192,
              name: '[hash:8].[name].[ext]',
              outputPath: 'fonts/'
            }
          }
        ]
      },
      {
        test: /\.(png|jpe?g|gif|svg|webp|tiff)(\?.*)?$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 8192,
              name: '[hash:8].[name].[ext]',
              outputPath: 'images/'
            }
          }
        ]
      }
Related