I want to use browser code in both the browser and the server. My code is basically React components. I want to review the code, get one compiled sheet app.jsand use it both in the browser and on the server:
<script src="/js/app.js" type="text/javascript" charset="utf-8" async></script>
var App = require('../assets/js/react/app');
But the browser does not know the windowobject, as I understand it. I cannot review requirethe server side code , an error occurs:
if (window.location.pathname == '/foo') {
^
ReferenceError: window is not defined
Here is the code:
... many React components go here ...
// and here is a call to window and its properties
if(window.location.pathname == '/foo') {
ReactDOM.render(
<MsgBox data={window.data} oInfo={window.oInfo} />,
document.getElementById('content-body')
);
ReactDOM.render(
<SearchBox />,
document.getElementById('searchBox')
);
}
browserify-handbook says it globalis an alias for window:
node, global - , , window . , global window.
, TypeError: Cannot read property 'pathname' of undefined:
// the code, I change window to global
if(global.location.pathname == '/foo') {
...
}
// and an error
if (global.location.pathname == '/foo') {
^
TypeError: Cannot read property 'pathname' of undefined
, window ?
, , :
var isBrowser;
if(typeof window != 'undefined') {
isBrowser = true
}
else
isBrowser = false;
? . Browserify window ? Browserify ?