search

Home  >  Q&A  >  body text

node.js - React + react-router `require.ensure 按需加载 服务端渲染出错`

我尝试使用require.ensure这个去做实现了按需加载的效果,但是因为我这边有做服务端渲染,所以现在是前端和服务端公用了一个路由控制器:

const routes = {
    component: Shell(Init),
    childRoutes: [
        {
            path: 'login',
            getComponent: (nextState, cb) => {
                require.ensure([], (require) => {
                    cb(null, require('../containers/login'))
                })
            }
        }
    ]
};

但是在服务端执行却报错了:

TypeError: require.ensure is not a function
    at Object.getComponent (D:/luoo/nodejs/app/routes/routes.jsx:49:25)
    at getComponentsForRoute (D:\luoo\nodejs\node_modules\react-router\lib\getComponents.js:29:16)
    at D:\luoo\nodejs\node_modules\react-router\lib\getComponents.js:41:5
    at D:\luoo\nodejs\node_modules\react-router\lib\AsyncUtils.js:84:5
    at Array.forEach (native)
    at mapAsync (D:\luoo\nodejs\node_modules\react-router\lib\AsyncUtils.js:83:9)
    at getComponents (D:\luoo\nodejs\node_modules\react-router\lib\getComponents.js:40:28)
    at finishEnterHooks (D:\luoo\nodejs\node_modules\react-router\lib\createTransitionManager.js:112:35)
    at runTransitionHooks (D:\luoo\nodejs\node_modules\react-router\lib\TransitionUtils.js:50:5)
    at runEnterHooks (D:\luoo\nodejs\node_modules\react-router\lib\TransitionUtils.js:93:10)

这个有哪个方案可以解决呢?

迷茫迷茫2785 days ago725

reply all(1)I'll reply

  • 黄舟

    黄舟2017-04-17 14:58:06

    When the webpack target is node, require is the native node.js require, and there is no require.ensure method.

    You can write a shim for the server environment

    reply
    0
  • Cancelreply