我正在尝试在我的应用程序中设置代码拆分/分块 - 通过路由,使用 require.ensure
。所以这是我的路线:
<Route path="profile"
getComponent={(location, cb) =>
{require.ensure(
[],
(require) => { cb(null, require('attendee/containers/Profile/').default) },
'attendee')}} />
以下是我的 webpack 配置中的相关行:
const PATHS = {
app: path.join(__dirname, '../src'),
build: path.join(__dirname, '../dist'),
};
const common = {
entry: [
PATHS.app,
],
output: {
path: PATHS.build,
publicPath: PATHS.build + '/',
filename: '[name].js',
chunkFilename: '[name].js',
sourceMapFilename: '[name].js.map'
},
target: 'web',
devtool: 'cheap-module-eval-source-map',
entry: [
'bootstrap-loader',
'webpack-hot-middleware/client',
'./src/index',
],
output: {
publicPath: '/dist/',
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"development"',
},
__DEVELOPMENT__: true,
}),
new ExtractTextPlugin('main.css'),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new webpack.ProvidePlugin({
jQuery: 'jquery',
}),
],
当我导航到路由中的页面时,我在日志中看到确实下载了所需的 block 。但是页面不会加载。
我在控制台中看到以下堆栈跟踪:
Uncaught TypeError: Cannot read property 'call' of undefined
t @ main.js:10
(anonymous function) @ main.js:44637
window.webpackJsonp @ main.js:40
(anonymous function) @ attendee.js:1
它提示的行是这样的:
return e[n].call(o.exports, o, o.exports, t)
第二行((匿名函数)@main.js:44637)本质上是这样的:
require('attendee/containers/Profile/').default
请注意,如果我执行 console.log(require('./attendee/containers/Profile/').default)
,我会得到一个函数作为输出,所以我不确定为什么它是未定义的。当然,当我这样做时,代码可以工作,但不再有分块。
所以我在 require
上做错了。知道它是什么吗?
顺便说一句,我在这个项目中使用了哈希历史 - 这可能是罪魁祸首吗?
更新:
还尝试了 this answer 中的 bundle-loader .相同的结果。
最佳答案
你快到了!试试这个:您需要在 require.ensure
的第一个参数中提前指定模块依赖项数组,而不是 []
显式将其设置为 ['与会者/容器/配置文件']
(location, cb) => {
require.ensure(['attendee/containers/Profile'], (require) => {
cb(null, require('attendee/containers/Profile').default)
})
}
关于javascript - 在 Webpack 和 React.js 中设置代码拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36988975/