我正在使用require.ensure在 react-router 路径创建分割点。但是,除了app.js
之外,我的构建目录仍然只有vendor.js
。我期待为我使用require.ensure
的每个路径单独的js文件。
我在每条路径上使用require.ensure
,如下所示:
<Route path= 'auth' getComponent={(nextState, callback) => {
require.ensure([], (require) => {
callback(null, require('containers/Authenticate/AuthenticateContainer.js').default)
}, 'auth')
}}/>
我的构建的web包配置输出如下所示:
output: {
path: PATHS.build,
filename: '/[name].[chunkhash].js',
chunkFilename: '/[chunkhash].js'
}
以下是我Use Api和route file的全部内容。
更新:我弄清楚我做错了什么。我的容器项目结构是这样的:
-app
-containers
-containerA.
-containerA.js
-containerB
-containerB.js
-containerC
-containerC.js
-index.js
问题:我仍然在路由文件中导出我需要的容器,如下所示:从'./containerB/containerB'导出containerB 删除index.js中的导出并直接从containerB.js中执行操作。
答案 0 :(得分:1)
确保获取您需要的参数数组模块。您需要为阵列提供要动态加载的模块名称。在您的情况下,提供'containers / Authenticate / AuthenticateContainer.js'以确保如下:
require.ensure(['containers/Authenticate/AuthenticateContainer.js'], (require) => {
callback(null, require('containers/Authenticate/AuthenticateContainer.js').default)
}, 'auth');
答案 1 :(得分:0)
我的一个项目遇到了同样的问题:我们使用Systemjs并决定切换到Webpack,因此它破坏了我们的System.import。我们通过替换:
来解决它System.import(modulePath)
.then(module => {
// Do things
})
使用:
new Promise((resolve, reject) => {
resolve(require(modulePath));
}).then((module) => {
// Do things
});
希望这有帮助
答案 2 :(得分:0)
我正在使用webpack 1.13.1,这是我的配置
output: {
path: PATHS.build,
filename: '[name].[hash].js',
publicPath:"/"
},
这是get component
的代码const lazyLoadSomeComponent = () => {
return {
getComponent: (location, callback)=> {
require.ensure([], require => {
callback(null, require("./componentpath")["default"]);
}, 'componentName');
}
}
};
然后在路线
<Route path="somepath" {...lazyLoadSomeComponent()} />
但是什么事情在这里?
对于进一步增强,我们可以使用以下方法
一次加载多个组件const LazyComponents = (pageName) => {
return {
getComponent: (location, callback)=> {
require.ensure([], require => {
switch(pageName){
case 'Component1':
callback(null, require("./components/component1")["default"]);
break;
case 'Component2' :
callback(null, require( "./components/component2" )["default"]);
break ;
}, "CombinedComponents");
}
}
};
然后在路线
<Route path="somepath" {...LazyComponents('Component1')} />
答案 3 :(得分:-1)
<Route path= 'auth' getComponent={(nextState, callback) => {
require.ensure(['containers/Authenticate/AuthenticateContainer.js'], (require) => {
const AuthenticateContainer = require('containers/Authenticate/AuthenticateContainer.js').default;
callback(null, <AuthenticateContainer />)
}, 'auth')
}}/>
试试这个。 我认为回调需要一个反应组件。