我发现虽然 Evan Henley 的方法更好,但我需要稍微改变它以使其与 Relay 兼容(与 ES6+ import)。
这需要在 ES6 导入中显式 bundle?lazy 才能与中继兼容。 This commit 显示了我发现的使其中继兼容的主要区别。
首先,在 Henley 的代码中,它需要配置 webpack 加载器和导入,例如:
import Landing from './components/Landing'
相比之下,我的方法不需要额外的 webpack 加载器配置,并在 import 中使用显式的 bundle-loader 延迟加载:
import Landing from 'bundle?lazy!./components/Landing'
Henley 的方法使路由文件导入更清晰。我的方法使它可以与 Relay 一起使用,并且通过import 进行更明确的代码拆分,而无需通过正则表达式进行任何额外的webpack.config.js 加载程序配置。
每个都很好,虽然我的方法是我发现使其中继兼容的唯一方法。
实施:
type GetComponent = (location?: string, cb: GetComponentCB) => void
/**
* Purpose: abbreviated expression so that we can read routes
*
* Background:
* - (failed) luqin/react-router-loader is awesome, but it is a Proxy and doesn't work with relay components.
* @see https://github.com/relay-tools/react-router-relay/issues/161
*
* - (failed) webpack dynamic requires need a hard path root (the rest can be an expression)
* at compile time and a regex is created
* @see https://webpack.github.io/docs/html#dynamic-requires
* @see http://stackoverflow.com/a/37228426/2363935
*
* - (succeeded ultimately) huge-app-splitting-refactor
* - uses bundle-loader, works with imports! and no path hardcoding!
* - approach doesn't work with Relay (quite as-is)
* - fixed approach with explicit bundle lazy imports!
* @see http://stackoverflow.com/a/37575707/2363935
* @see http://henleyedition.com/implicit-code-splitting-with-react-router-and-webpack/
* @see https://github.com/echenley/react-router-huge-apps-refactor
*
* @param component
* @returns {function()}
*/
export function lazy (lazyModule: Function): GetComponent {
if (!lazyModule) {
throw new Error('lazy() did not find the given module. Check to be sure your import path is correct, and make sure you are pointing at a file with a ****default export****.')
}
return (location, cb) => {
lazyModule((module) => {
cb(null, module.default)
})
}
}
用法:
/* eslint-disable flowtype/require-valid-file-annotation */
import OrganizationQueries from '../../queries/OrganizationQueries'
import React from 'react'
import {Route} from 'react-router'
import {lazy} from '../../config/routes'
import Organization from 'bundle-loader?lazy!./Organization'
// protected by parent route
export default (
<Route>
<Route path='/organization' getComponent={lazy(Organization)} queries={OrganizationQueries} />
</Route>
)