Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a string to another string with webpack?

Tags:

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?

like image 771
李鸿章 Avatar asked Nov 08 '17 16:11

李鸿章


2 Answers

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
like image 140
vma Avatar answered Oct 21 '22 18:10

vma


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'
        }
      }
    ]
  }
}
like image 22
d4nyll Avatar answered Oct 21 '22 18:10

d4nyll