Uglifyjs: Injected global constant string interpreted as regex

Created on 29 Dec 2015  路  4Comments  路  Source: mishoo/UglifyJS

Through the DefinePlugin for webpack, I'm injecting some global configuration constants into my code. One of them, __BASE__, is defined before injection as a string like __BASE__ = '/some/cool/path/'. When the source code trying to use __BASE__ is run through UglifyJS, however, the variable is interpreted as a regular expression and I get:

ERROR in app.f0ac8ef8b75ecda96357.js from UglifyJs
Invalid flags supplied to RegExp constructor 'cool'

It works fine if the constant is created as a string _in the code_, or if injected without the outer slashes, but seems to be misinterpreted if injected as is. I'm assuming this is because it's ambiguous to the parser that way and the parser assumes regex > string when it sees the first slash.

Most helpful comment

Nothing a good JSON.stringify won't fix, it seems.

All 4 comments

Nothing a good JSON.stringify won't fix, it seems.

In my case I had a webpack.DefinePlugin which set a value on process.env.API_URL. Using JSON.stringify to wrap the value helped.

Can you guys give an example of what you mean by using JSON.stringify?

@trusktr :

    new webpack.DefinePlugin({
      'process.env': {
        STRIPE_KEY: JSON.stringify(process.env.STRIPE_KEY),
      },
    }),
Was this page helpful?
0 / 5 - 0 ratings