webpack transform/replace css url

Viewed 1921

I am using webpack with css-loader, style-loader and ExtractTextPlugin to generate css files.

I would like to replace certain URLs used in those CSS files.

For example:

url('../fonts/icomoon.ttf?asbl3h') 
url('../../fonts/whatever.ttf?asbl4h') 

should become

url('fonts/icomoon.ttf?asbl3h')
url('fonts/whatever.ttf?asbl4h') 

The fonts are not necessarily in the right relative folder. I am using webpack to generate css with a plugin to copy all the fonts to a certain folder.

What is the best way to do this?

As a fallback it would be ok to just perform string replaces.

1 Answers

Definitely not sure if this is the best way, but for anyone who's faced with having to fall back on string replacement, here's an outline of how I hacked around a similar problem using string-replace-loader and defining a special rule for the files that need modification:

  module: {
    rules: [
      {
        test: REGEX_MATCHING_ONLY_FILES_TO_BE_MODIFIED,
        use: [
          {
            loader: 'string-replace-loader',
            options: {
              search: "url\\('\(.*)fonts/", // these regular expressions should work for the example paths in the question
              replace: 'url(fonts/\1)',
              flags: 'g',
            }
          },
          // any other loaders you need, e.g. css-loader //
        ],
      },
    ],
  }

(Credits: jakenuts' response on webpack-contrib#27 put me on the right track.)

Related