我正在使用,并希望使用webpack 2.0支持的动态导入()来导入基于变量字符串的模块。
我看过官方提案(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;页面/默认/主页/index.js
import React from 'react';
export const HomePage = () => {
return (
<div>
I'm the default HomePage
</div>
);
}
export default HomePage;坏掉的服务/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更改为
工作服务/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;它起作用了。

绝对路径是在环境变量的帮助下建立在创建-反应-应用程序中的东西。
.env
NODE_PATH=src/我需要通过这种方式动态加载模块来构建多租户概念的证明。如何修复损坏的LazyLoad,以便将字符串作为支柱传递,并让LazyLoad组件从该字符串支柱动态加载组件?
发布于 2017-07-12 23:58:51
只有部分动态语句被允许用于import()。
在您的AppRoutes.js中,您可以这样做:
...
<LazyLoad
modulePath='HomePage'
getComponent={() => import('pages/default/HomePage')}
{...matchProps}
/>然后在您的LazyLoad组件中执行以下操作:
componentDidMount() {
import(`pages/default/${this.props.modulePath}/index.js`)
.then(module => module.default)
.then(AsyncModule => this.setState({AsyncModule}))
}完全动态的语句(如import(foo) )将失败,因为webpack至少需要一些文件位置information.The import()必须至少包含一些有关模块所在位置的信息,因此绑定可以限制在特定目录或文件集上。
https://stackoverflow.com/questions/44166393
复制相似问题