李鸿章
李鸿章

Reputation: 373

How to replace a string to another string with webpack?

There are string holders everywhere in my code(.js, .ts... ), such as '__DOMAIN_HOLDER__/id/20180101', and I want to replace '__DOMAIN_HOLDER__' to let say 'https://www.example.com'.

How to accomplish this with webpack of latest version?

Upvotes: 19

Views: 24601

Answers (2)

d4nyll
d4nyll

Reputation: 12627

Instead of defining a global variable, you can instead use string-replace-loader

module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /\.js$/,
        loader: 'string-replace-loader',
        options: {
          search: '__DOMAIN_HOLDER__',
          replace: 'https://www.example.com',
          flags: 'g'
        }
      }
    ]
  }
}

Upvotes: 20

vma
vma

Reputation: 1626

You can use webpack's DefinePlugin:

https://webpack.js.org/plugins/define-plugin/#usage

new webpack.DefinePlugin({
  __DOMAIN_HOLDER__: 'value'
})

and the variable will become available for you to use. Ofcourse, you would have to use it as a variable

`${__DOMAIN_HOLDER__}/id/20180101`

would be replaced with

value/id/20180101

Upvotes: 19

Related Questions