I'm trying to use isomorphic rendering in React so I can output static HTMLs as documentation for my application.
The problem is that I have a particular component that only runs on the client, because it references window
. The solution is obvious: Not to render it on the server. Yes, I can not to render it on the server, but still, I need it to be included in my webpack
bundle so I can render it on the client. The problem is that, the code that prevents my component from rendering on the server is:
function isServer() {
return ! (typeof window != 'undefined' && window.document);
}
But isServer()
is also true
when webpack
is bundling, and I want it to work normally while webpack
is running.
So, how do I detect that webpack
is running?
I'm looking for something like this:
function isWebpack() {
// what do I put here?
}
Now I can render my client-only component normally if isServer()
and !isWebpack()
.
Thanks!
EDIT
This is the component I'm trying to build:
function isServer() {
return ! (typeof window != 'undefined' && window.document);
}
import React from 'react';
const LED = React.createClass({
render: function () {
if(!isServer()) {
var LiveSchemaEditor = require('../../src/components/LiveSchemaEditor.js');
return <LiveSchemaEditor />;
}
return <div>I AM IN THE SERVER</div>;
}
});
export default LED;
What's bugging me is that the webpack
bundle includes the content of LiveSchemaEditor.js
but it still prints I AM IN THE SERVER
while on client. This doesn't make sense.
Put this in your webpack config under plugins:
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
APP_ENV: JSON.stringify('browser')
}
}),
With that you can check if you're running in a browser or not this way:
if (process.env.APP_ENV === 'browser') {
const doSomething = require('./browser-only-js');
doSomething();
} else {
const somethingServer = require('./server-only-js');
somethingServer();
}
if (process.env.APP_ENV !== 'browser') {
const somethingServer = require('./server-only-js');
somethingServer();
}
Because these environment variables get replaced during the build, Webpack will not include resources that are server-only. You should always do these kinds of things in an easy way, with a simple, direct compare. Uglify will remove all dead code.
Since you used a function before and the function is not evaluated during build, Webpack wasn't able to know what requires it could skip.
(The NODE_ENV
-variable should always be set to production
in production mode, since many libraries including React use it for optimisations.)
You could also do this -
typeof __webpack_require__ === 'function'
I'm guessing this might change at anytime so use with caution. :/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With