svg-sprite-loader icon indicating copy to clipboard operation
svg-sprite-loader copied to clipboard

Webpack 5 / MiniCssExtractPlugin issue

Open just-website opened this issue 4 years ago • 2 comments

Problem In bundle with MiniCssExtractPlugin all path to backgrond-images on svg in styles replaced from sprite url to absolute path file system.

There is an open same issue. The difference is only in the version of the packages

  • Node v14.16.1
  • Webpack v5.41.0
  • svg-sprite-loader v6.0.9

just-website avatar Jul 06 '21 19:07 just-website

@just-website, hi! Do you have some temporary workaround?

kodmigor avatar Sep 08 '21 09:09 kodmigor

Good day! 😃

For everyone who has the same issue, I wrote a somewhat dirty fix for that by creating a new plugin which extends from the SpriteLoaderPlugin:

const SpriteLoaderPlugin = require('svg-sprite-loader/plugin');
const { replaceSpritePlaceholder } = require('svg-sprite-loader/lib/utils');

class MiniCssExtractSpriteLoaderPlugin extends SpriteLoaderPlugin {
  apply(compiler) {
    super.apply(compiler);

    if (compiler.hooks) {
      compiler.hooks.thisCompilation.tap(super.NAMESPACE, (compilation) => {
        compilation.hooks.afterOptimizeChunks.tap(super.NAMESPACE, (chunks) =>
          chunks.forEach((chunk) => {
            compilation.chunkGraph
              .getChunkModules(chunk)
              .filter((module) => module.type === 'css/mini-extract')
              .forEach((module) => {
                // eslint-disable-next-line no-param-reassign
                module.content = Buffer.from(
                  replaceSpritePlaceholder(
                    module.content.toString(),
                    super.getReplacements(),
                  ),
                );
              });
          }),
        );
      });
    }
  }
}

Now you can just use the new MiniCssExtractSpriteLoaderPlugin in your webpack config and it should work. Note: I wrote this for our own purposes / usecases and not as a general solution so older webpack, plugin or node versions might won't work

KingSora avatar Dec 10 '21 13:12 KingSora