Disable asset bundling in Webpack 5

Viewed 612

When I reference an asset in Webpack 5 it creates a copy of it by default. For example a font file in ./assets/fonts/myfont.woff2 gets copied to ./b27297c148a7ef314ce2.woff2 which is very useful when working with a source and a dist folder. Howerver, I need to use the same asset directory from my source files and the bundled css file. Is there a way to disable the file copying and only update the path to the ressource files according to the destination of the bundled output file?

Update:

I've managed to set the copy destination equal to the source destination of my asset files:

/*webpack.config.js*/
module.exports = {
  output: {
    assetModuleFilename: '[file]'
  },
};

However, this is not ideal as all files get overwritten by themselves.

1 Answers

I found the following solution. In this example all files inside of the /asset folder are kept in place:

/*webpack.config.js*/

module.exports = {
  module: {
    rules: [
      {
        test: /^assets\/.*$/i,
        type: 'asset/resource',
        /* do not emit copies of files */
        generator: {
          emit: false
        }
      },
    ],
  },
  output: {
    /* use original file-path in generated output files */
    assetModuleFilename: '[file]'
  },
};

Unfortunately I found nothing about it in the official documentation, the answer is based on: https://github.com/webpack/webpack/pull/12871

For some reason this seems not to work with the watch option enabled (tested with webpack 5.44.0 and webpack-cli 4.7.2.)

Related