19

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?

2 Answers 2

20

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'
        }
      }
    ]
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I added "string-replace-loader": "^3.0.3", to my package.json to make this work - thanks.
19

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

2 Comments

Thank you! Is possible to achieve the same result with the same codebase using gulp?
This doesn't work on all strings but only globals. The docs are terrible on this.. it's very confusing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.