Va1 / string-replace-loader

Replace loader for Webpack
MIT License
250 stars 57 forks source link

Cannot supply flags when constructing one RegExp from another #31

Closed shirishp closed 6 years ago

shirishp commented 7 years ago

Configuration

module.exports = {
  // ... 
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'string-replace',
        query: {
          multiple: [
             { search: '{vars.id}', replace: '90', flags: 'g' },
             { search: '{path.api}', replace: 'http://localhost:9000', flags: 'g'}
          ]
        }
      }
    ]
  }
}

Error:

WARNING in <file_name>
Module build failed: TypeError: Cannot supply flags when constructing one RegExp from another
    at new RegExp (native)
    at processOptions (node_modules/string-replace-loader/index.js:8:24)
    at node_modules/string-replace-loader/index.js:31:16
    at Array.forEach (native)
    at Object.module.exports (node_modules/string-replace-loader/index.js:29:22)
 @ ./src/javascript/scripts \.js$

This seems to be happening because https://github.com/Va1/string-replace-loader/blob/master/index.js#L29 returns source as regular expression, and then the regular expression is again passed to RegEx constructor at https://github.com/Va1/string-replace-loader/blob/master/index.js#L7

Workaround

For now, changing the configuration to following seems to work:

module.exports = {
  // ... 
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'string-replace',
        query: {
          multiple: [
             { search: new RegExp('{vars.id}', 'g'), replace: '90'},
             { search: new RegExp('{path.api}', 'g'), replace: 'http://localhost:9000'}
          ]
        }
      }
    ]
  }
}

Notice the multiple array using search option as RegExp instead of plain string without flags option.

cdll commented 7 years ago

did it above worked cause that didnt work for me, as:

      {
        test: /\.coffee$/
        ,loader: "string-replace"
        ,query: {
          multiple: [
            {
              search: new RegExp('@@basepath', 'g')
              ,replace: '/public' 
            }
            ,{
              search: new RegExp('@@environment', 'g')
              ,replace: 'dev' 
            }
          ]
        }
      }

@shirishp any suggestion for me ?whats wrong with my code?

shirishp commented 7 years ago

@cdll I can't think of any reason why it wouldn't work. Following thing works in browser console:

"something @@basepath".replace(new RegExp('@@basepath', 'g'), '/public')
// => "something /public"

I would recommend trying to replace something else and see if that string is replaced to confirm this loader is actually triggering.

Va1 commented 6 years ago

guys, supplying anything complex in the loader options is not possible, because webpack internally does JSON.stringify and JSON.parse for the em. refer to docs before doing hacky stuff in the future.