Browsing code on the server: how to get the "window", "location" and other properties of the "window" and usually browser objects?

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:

// in a browser
<script src="/js/app.js" type="text/javascript" charset="utf-8" async></script>

// on a server
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 ?

+4
3

.

Delphi runtime/design-time,

if (state in csDesigning) do 
begin 
    ... // Bad juju 
end
else do 
begin
    ... // Bad juju
end

. . , , . .

browser.js
common.js // shared kernel (browserify)
server.js
+5

- , , location. , , , global.location?

, URL- http , . , .

+1

You must do this using the package jsdom. https://github.com/tmpvar/jsdom

0
source

Source: https://habr.com/ru/post/1621372/


All Articles