webpack: DefinePlugin doesn't work inside React Components
Hey there. I have a very strange issue with my build. My global variables replaced by webpack inside “normal” files, but not replaced inside files with react.
My config looks like this (it’s too big and not interesting):
const GLOBALS = {
__API__: 'https://my-domain.com/api',
__ENV: 'development',
'process.env.NODE_ENV': '"production"'
};
const serverConfig = {
...
module: {
...config.module,
loaders: [
...config.module.loaders,
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
cacheDirectory: true,
query: {
babelrc: false,
presets: ['react', 'es2015-node5', 'stage-0'],
plugins: []
}
},
sassLoader.development
]
},
plugins: [
...config.plugins,
new webpack.DefinePlugin({
'__SERVER__': true,
...GLOBALS
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
]
};
And I see inside my build file for node that into some files variable SERVER was replaced. It’s a normal file without jsx and react. But into another files with react and jsx - not. So a catch an error
ReferenceError: __SERVER__ is not defined
For example inside my redux/modules/window/windowReducer.js
const initialState = {
viewport: {
width: true ? 1366 : window.innerWidth, // Default width for server-side rendering
height: true ? 768 : window.innerHeight // Default height for server-side rendering
},
body: {
scrollTop: true ? 0 : document.body.scrollTop,
scrollHeight: true ? 0 : document.body.scrollHeight
}
};
But inside components/Player/index.js
...
render() {
if (__SERVER__) return null;
...
}
About this issue
- Original URL
- State: closed
- Created 8 years ago
- Reactions: 52
- Comments: 18 (6 by maintainers)
+1
Please use the ‘thumbs up’ button on the original issue at the top instead. It increases visibility to webpack maintainers sorting issues by ‘thumps up’ reactions. Also, it doesn’t spam people who are already subscribed to this issue. 😃
Hey ! I am running into this issue awkardly. Actually I move from webpack 3.0.0 to 4.17.1. And my webpack config haven’t change much. this is my function, the way it is, untouched
And those variables like NGBOOSTED_VERSION are undefined.
I check on the website and I didn’t see new stuff or changes. And i am suprised. Anyone have any idea of what causes that trouble ?
Any update on this issue ?
That’s strange. Maybe as a workaround you could do something like:
Not sure if ongoing concern, I am currently running: react: ^16.2.0, webpack: ^3.8.1
As suggested by #2427, I am able to get the correct response via JSON.stringify-ing the values as follows:
+1
+1
@bebraw it doesn’t work not only inside
render()
, inside any react component lifecycle method (constructor, componentWillReceiveProps, etc.)