user2595304
user2595304

Reputation: 236

Webpack's define plugin: variable is not defined

I'm trying to pass some environment related variables into my React components using Webpack's DefinePlugin. Client side part works great, server side part returns 'MYVARIABLE is not defined'.

I'm using Webpack's Node.JS api. Important parts are below. Am I doing something wrong? Thanks

webpack.config.js

...
webpackConfig.plugins = [
  new webpack.DefinePlugin({
    MYVARIABLE: 'test-value'
  })
]
...

server.js

...
import webpack from 'webpack'
import webpackConfig from '../config/webpack.config'
...
var compiler = webpack(webpackConfig)
...

component file

...
console.log(MYVARIABLE)
...

result

ReferenceError: MYVARIABLE is not defined
....

Upvotes: 2

Views: 10762

Answers (1)

davidmars
davidmars

Reputation: 689

You have to JSON.stringify('your-value').

According https://webpack.js.org/plugins/define-plugin/ :

because the plugin does a direct text replacement, the value given to it must include actual quotes inside of the string itself. Typically, this is done either with either alternate quotes, such as '"production"', or by using JSON.stringify('production').

so your webpack.config.js should be...

webpackConfig.plugins = [
 new webpack.DefinePlugin({
  MYVARIABLE: JSON.stringify('test-value')
 })
]

Upvotes: 7

Related Questions