Gre*_*een 5 javascript browserify reactjs react-jsx
我想在浏览器和服务器上使用浏览器代码.我的代码基本上是React组件.我想app.js在浏览器和服务器上浏览代码,获取一个编译表并使用它们:
// 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');
Run Code Online (Sandbox Code Playgroud)
但是浏览器window根据我的理解不知道对象.我无法require在服务器端浏览代码,抛出错误:
if (window.location.pathname == '/foo') {
^
ReferenceError: window is not defined
Run Code Online (Sandbox Code Playgroud)
这是代码:
... 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')
);
}
Run Code Online (Sandbox Code Playgroud)
browserify-handbook说这global是一个别名window:
在节点中,
global是附加全局变量的顶级范围,类似于window浏览器中的工作方式.在browserify中,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
Run Code Online (Sandbox Code Playgroud)
那么如何应对window这种情况呢?
一个想法是使用变量,我现在这样做:
var isBrowser;
if(typeof window != 'undefined') {
isBrowser = true
}
else
isBrowser = false;
Run Code Online (Sandbox Code Playgroud)
但这是最好的方式吗?这对我来说有点奇怪.Browserify for window和其他本机浏览器中是否有特殊的手段?在这种情况下使用Browserify的最佳做法是什么?
这样做你会遇到麻烦.
它让我想起Delphi的运行时/设计时包,它包含了很多
if (state in csDesigning) do
begin
... // Bad juju
end
else do
begin
... // Bad juju
end
Run Code Online (Sandbox Code Playgroud)
不是个好主意.从长远来看,你会失去理智.相反,创建一个包含共享代码的共享内核,而不是其他内容.服务器永远不应该看到窗口变量.
browser.js
common.js // shared kernel (browserify)
server.js
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
485 次 |
| 最近记录: |