2016-06-25 57 views
-1

我使用react_on_rails gem和im嘗試渲染服務器的組件。「文檔未定義」Webpack + React on Rails +服務器渲染

當我直接從應用程序使用組件,它工作正常!

import Hello from "../components/Hello" 

ReactOnRails.register({ 
    Hello 
}) 

但是,當我嘗試使用一個包,該應用程序會引發錯誤。

import { Ballon } from "foo-package" 
import Hello from "../components/Hello" 

ReactOnRails.register({ 
    Ballon, 
    Hello 
}) 

ERROR in SERVER PRERENDERING 
Encountered error: "ReferenceError: document is not defined" 

有人知道爲什麼嗎?

+1

它不起作用的原因是你導入的包不是服務器渲染友好的。在服務器端,node.js不是全局變量。你可以嘗試在你的Hello Component的'render'或'componentWillMount'中使用'document',並且會發生同樣的錯誤。 –

回答

0

我發現了! 'foo-package'使用非同構包。它打破了服務器渲染。該軟件包是react-google-chart。

1

窗口和文檔是僅在瀏覽器環境中可用的全局變量。

當您在服務器上呈現時,您沒有該環境。當您處於node.js環境中時,您需要保護您的代碼並跳過調用這些對象的任何函數。例如:

if (typeof document !== 'undefined') { 
    // Do your document thing here 
} else { 
    console.log("We're on server") 
} 
相關問題