所以我正在使用https://github.com/mhart/react-server-example/blob/master/server.js来解决React中的服务器端渲染问题。它利用了browserify。
示例是一个平面文件夹结构,因为它就是一个例子。所以下面是我的一些令我感到困惑的变化。
/server/controllers/bundles.jsx
有此
browserify()
.add('./app/scripts/checkout.jsx')
.transform(literalify.configure({
'react': 'window.React',
'react-dom': 'window.ReactDOM',
}))
.bundle()
.pipe(res)
此时我收集到即使我嵌套在一个文件夹中,browserify仍在root工作。同时在checkout.jsx
里面我有这个:
require('./app/scripts/components/checkout/layout');
当我启动服务器时,它无法找到该文件。我也尝试过./components/checkout/layout
,因为它与checkout.jsx
相关。
无论我尝试什么,我的服务器都说无法找到布局模块。
更新我为__dirname
添加了console.log并看到了/app/scripts
因此它让我觉得require('components/checkout/layout')
应该点击/app/scripts/components/checkout/layout
但它仍然没有找到。我还应该注意,该文件确实module.exports = Layout
,并且在服务器上使用时,在另一个文件中被要求正常。
答案 0 :(得分:2)
您需要添加文件扩展名(.jsx
)。
基本上,节点中的require
有一堆规则,all outlined in the docs here。
在您的情况下,最相关的是这部分:
require(X) from module at path Y
1. If X is a core module,
a. return the core module
b. STOP
2. If X begins with './' or '/' or '../'
a. LOAD_AS_FILE(Y + X)
b. LOAD_AS_DIRECTORY(Y + X)
3. LOAD_NODE_MODULES(X, dirname(Y))
4. THROW "not found"
LOAD_AS_FILE(X)
1. If X is a file, load X as JavaScript text. STOP
2. If X.js is a file, load X.js as JavaScript text. STOP
3. If X.json is a file, parse X.json to a JavaScript Object. STOP
4. If X.node is a file, load X.node as binary addon. STOP
您正在点击#2,然后转到LOAD_AS_FILE
,默认情况下jsx
个文件都没有,所以您需要扩展才能使用匹配#1。