react server render的坑
By admin
首先是各种在node_modules中的外部依赖,需要用webpack-node-externals放到externals中
如果是使用了nodejs内置的工具,需要在externals中添加额外配置,比如 {http: ‘commonjs http’, fs: ‘commonjs fs’ }
然后是禁止使用各种window全局变量,使用各种挂在window下的全局方法之前需要先判断一下方法是否存在。
在webpack编译过的server环境中__dirname和__filename都取不到值,需要用definePlugin预先在webpack的配置中取值。
各种import进来的sass,less,css还有base64的图片一定要用extract-text-webpack-plugin去除。
react-router的各个组件经过代码分割之后是异步加载,在服务端这里要变成同步是个问题。在react-router文档说明如下,所以目前能用的解决方法就是为服务端另写一份路由,只是要在这个问题解决之前要暂时维护两份本应该统一的路由文件。
<p class="cye-lm-tag">
We’ve tried and failed a couple of times. What we learned:
</p>
<ol>
<li>
You need synchronous module resolution on the server so you can get those bundles in the initial render.
</li>
<li>
You need to load all the bundles in the client that were involved in the server render before rendering so that the client render is the same as the server render. (The trickiest part, I think its possible but this is where I gave up.)
</li>
<li>
You need asynchronous resolution for the rest of the client app’s life.
</li>
</ol>
<p class="cye-lm-tag">
We determined that google was indexing our sites well enough for our needs without server rendering, so we dropped it in favor of code-splitting + service worker caching. Godspeed those who attempt the server-rendered, code-split apps.
</p>
</div>
</div>
</div>
redux在服务端传递初始状态的问题。