我正在使用Create-React-App,并希望使用webpack 2.0支持的动态import()根据变量字符串导入模块。
我已经查看了官方提案(https://github.com/tc39/proposal-dynamic-import),似乎可以做到这样:
.env文件。
我需要以这种方式动态加载模块,以构建多租户的概念验证。我该如何修复损坏的LazyLoad组件,以便可以传递一个字符串作为属性,并使LazyLoad组件从该字符串属性动态加载组件?
我已经查看了官方提案(https://github.com/tc39/proposal-dynamic-import),似乎可以做到这样:
import(`./language-packs/${navigator.language}.js`)
但是当我尝试类似的东西时,它会出错。
AppRoutes.js
import LazyLoad from 'services/LazyLoad';
export class AppRoutes extends React.Component {
render() {
return (
<Switch>
<Route
exact path="/"
render={(matchProps) => (
<LazyLoad
absoluteModulePath='pages/default/HomePage'
getComponent={() => import('pages/default/HomePage')}
{...matchProps}
/>
)}
/>
</Switch>
);
}
}
export default AppRoutes;
pages/default/HomePage/index.js
import React from 'react';
export const HomePage = () => {
return (
<div>
I'm the default HomePage
</div>
);
}
export default HomePage;
损坏的 services/LazyLoad/index.js
import React from 'react';
export class LazyLoad extends React.Component {
...
componentDidMount() {
import(this.props.absoluteModulePath) // Critical dependency: the request of a dependency is an expression
.then(module => module.default)
.then(AsyncModule => this.setState({AsyncModule}))
}
...
}
export default LazyLoad;
错误:
当我把LazyLoader更改为WORKING services/LazyLoad/index.js时import React from 'react';
export class LazyLoad extends React.Component {
...
componentDidMount() {
this.props.getComponent()
.then(module => module.default)
.then(AsyncModule => this.setState({AsyncModule}))
}
...
}
export default LazyLoad;
它有效。
绝对路径是通过环境变量在create-react-app中构建的内容。.env文件。
NODE_PATH=src/
我需要以这种方式动态加载模块,以构建多租户的概念验证。我该如何修复损坏的LazyLoad组件,以便可以传递一个字符串作为属性,并使LazyLoad组件从该字符串属性动态加载组件?
'./pages/default/HomePage'
作为路径,而不是pages/default/HomePage
吗? - Michael Lyons/pages...
,不然我也不知道。关于打包分离,我使用React-Router的getComponent,并且使用require.ensure
。抱歉,我没有通过import进行懒加载的经验。 - Michael Lyons