ReferenceError: window is not defined when requiring certain 3rd party libs
I get the ReferenceError: window is not defined when requiring certain libs that make use of the window object.
Heres the full stack trace:
ReferenceError: window is not defined
at <path-to-project>/node_modules/chartist/dist/chartist.js:715:5
at Chartist.version (<path-to-project>/node_modules/chartist/dist/chartist.js:11:22)
at Object.<anonymous> (<path-to-project>/node_modules/chartist/dist/chartist.js:15:2)
at Module._compile (module.js:456:26)
at Module._extensions..js (module.js:474:10)
at reactTransform (<path-to-project>/gulpfile.js:58:5)
at Object.Plugin.reactTransform (<path-to-project>/node_modules/gulp-render/index.js:80:7)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
Is there any workaround for this?
Btw Im using your react starterkit https://github.com/kriasoft/react-starter-kit
When doing server-side rendering?
This happens when gulp-render is called from the 'pages' task in from the gulp.js file in react-starter-kit.
Again, it only happens when i have required a lib that uses window. If i temporarily remove that require it all works as intended.
It's tricky with 3rd party React components, because they often have no if (canUseDOM) { .. } checks before accessing window.. one way to deal with it is to declare a global window / document variable + some properties which might be used by 3rd party components, for example, you can add this line to your gulpfile.js (or server.js): global.window = { addEventHandler = () {} }. Another approach is not to render these components in your app if window var is not available, something like:
var React = require('react');
var { canUseDOM } = require('react/lib/ExecutionEnvironment');
var Chart = canUseDOM ? require('react-chart') : React.DOM.div;
var MyComp = React.createClass({
render() {
return <div>
<p>Chart Component:</p>
<Chart />
</div>;
}
});
module.exports = MyComp;
Yea okay i understand. Thanks for the help i think either of your examples will work fine.
Just one question; as i said before I'm using this gulp plugin as it was implemented in the starter kit, what are the benefits of using this plugin to generate "reactified" html files as opposed to just rendering the react markup server side with React.renderComponentToString() ?
@yemi I think it may only be useful if you want to precompile your React-based website for hosting in CDN (e.g. GitHub Pages).
@yemi you may also want to look at this example of server-side rendering (without gulp-render)
https://gist.github.com/koistya/24715d295fbf710d1e24
Thanks a lot! Btw, I really like what you've done with gulp-render and react starter kit
Thanks :)