React-router getComponent不能是System.import()路径名变量

时间:2016-12-14 21:08:24

标签: javascript react-router es6-modules

我正在尝试使用React Router的getComponent()方法动态加载路由。我想将动态加载(通过System.import())抽象为一个带有路径名称的函数。但是,当我尝试这个时,我收到以下错误:

  

无法找到模块'features / auth / containers / LoginFormContainer'。

不起作用

function loadRoute(path) {
    return function(location, callback) {
        console.log('path?', path); // => 'features/auth/containers/LoginFormContainer'
        System.import(path)
            .then((cb => module => {
                return cb(null, module.default)
            })(callback))
            .catch(err => console.error('Dynamic route chunk loading failed', err));
    }
}

export const routes = [
    {
        path: '/login',
        getComponent: loadRoute('features/auth/containers/LoginFormContainer')
    },
    ...

如果我尝试在路径中进行硬编码,它会按预期工作:

如,

正常工作

function loadRoute(path) {
    return function(location, callback) {
        System.import('features/auth/containers/LoginFormContainer')
            .then((cb => module => {
                return cb(null, module.default)
            })(callback))
            .catch(err => console.error('Dynamic route chunk loading failed', err));
    }
}

为什么这不起作用,我如何指定System.import加载的路径?

更新

以下也不起作用,导致相同的错误:

const fn = (cb) => (module) => {
    const Component = module.default;
    return cb(null, Component);
}

const loadRoute = (path) => (location, callback) => {
    System.import(path)
        .then(fn(callback))
        .catch(e => console.warn('Could not load route chunk', e));
}

export const routes = [
    {
        path: '/login',
        //component: LoginForm
        getComponent: loadRoute('features/auth/containers/LoginFormContainer')
    },

2 个答案:

答案 0 :(得分:0)

如果我没有错误,将./添加到路径名称的开头将解决问题

答案 1 :(得分:0)

使用webpack加载react-router配置时,由System.import()指定的webpack can't very well statically analyze the variable name。因为我的目标是减少样板并创建动态解决方案,所以现在已经足够了:

const loadAsync = (promise) => (location, callback) => {
    promise
        .then(module => callback(null, module.default))
        .catch(e => console.warn('Could not load route component', e));
}

export const routes = [
    {
        path: '/login',
        getComponent: loadAsync(System.import('components/LoginForm'))
    },
    ...
}