Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string replace loader not working with webpack 3

I am using webpack 3 & trying to use string replace loader.

This code use to work in webpack1.X

module: {
    loaders: [
      {
        test: /fileName\.js$/,
        loader: 'string-replace',
        query: {
          search: 'jQuery',
          replace: 'window.$'
        }
      }
    ]
  }

I have tried this as well:

module: {
        loaders: [
          {
            test: /fileName\.js$/,
            loader: 'string-replace-loader',
            query: {
              search: 'jQuery',
              replace: 'window.$'
            }
          }
        ]
      }

What do I need to do to ensure this loader works in webpack 3. There are no errors but string is not getting replaced in the target file.

like image 274
OpenStack Avatar asked Aug 20 '17 13:08

OpenStack


2 Answers

Have you tried adding flags: 'g' to the query option:

query: {
    search: 'jQuery',
    replace: 'window.$'
    flags: 'g'
}
like image 146
harshes53 Avatar answered Oct 06 '22 04:10

harshes53


In Webpack 3 and Webpack 4 you can use the string-replace-webpack-plugin to perform string replacement by pattern at compile time.

For Webpack 3, add the following code to your webpack.config.js:

var StringReplacePlugin = require("string-replace-webpack-plugin");
module.exports = {
   module: {
      loaders: [
         // configure replacements for file patterns
         { 
            test: /fileName\.js$/,
            loader: StringReplacePlugin.replace({
                replacements: [
                    {
                        pattern: /jQuery/g,
                        replacement: function (_match, _p1, _offset, _string) {
                            return "window.$";
                        }
                    }
                ]})
            }
      ]
   },
   plugins: [
      // an instance of the plugin must be present
      new StringReplacePlugin()
   ]
}

For Webpack 4, the syntax is as follows:

var StringReplacePlugin = require("string-replace-webpack-plugin");
module.exports = {
   module: {
      rules: [{ 
         test: /fileName\.js$/,
         use: [{
            loader: StringReplacePlugin.replace({
               replacements: [{
                  pattern: /jQuery/g,
                  replacement: function (_match, _p1, _offset, _string) { return "window.$"; }
                  }]
            })
         }]
      }]
   },
   plugins: [
      new StringReplacePlugin()
   ]
}
like image 23
Alex Walker Avatar answered Oct 06 '22 04:10

Alex Walker