Dmi*_*dov 6 javascript lazy-loading reactjs webpack react-router
我正在尝试在我的应用程序中设置代码拆分/分块 - 通过路由,使用require.ensure.所以这是我的路线:
<Route path="profile"
getComponent={(location, cb) =>
{require.ensure(
[],
(require) => { cb(null, require('attendee/containers/Profile/').default) },
'attendee')}} />
Run Code Online (Sandbox Code Playgroud)
以下是我的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',
}),
],
Run Code Online (Sandbox Code Playgroud)
当我导航到路径中的页面时,我在日志中看到所需的块已下载.但是页面没有加载.
我在控制台中看到以下堆栈跟踪:
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
Run Code Online (Sandbox Code Playgroud)
它抱怨的界限是这样的:
return e[n].call(o.exports, o, o.exports, t)
Run Code Online (Sandbox Code Playgroud)
第二行((匿名函数)@main.js:44637)基本上是这样的:
require('attendee/containers/Profile/').default
Run Code Online (Sandbox Code Playgroud)
注意,如果我这样做console.log(require('./attendee/containers/Profile/').default),我会得到一个函数作为输出,所以我不确定为什么它是未定义的.当然,当我这样做时,代码可以工作,但是不再有任何分块.
所以我做错了require.知道它是什么?
顺便说一句,我在这个项目中使用哈希历史 - 这可能是罪魁祸首吗?
更新:
还尝试了在这个答案中的bundle-loader .结果相同.
小智 0
你快到了!试试这个:您需要在第一个参数中提前指定模块依赖项的数组,require.ensure而不是将[]其显式设置为['attendee/containers/Profile']
(location, cb) => {
require.ensure(['attendee/containers/Profile'], (require) => {
cb(null, require('attendee/containers/Profile').default)
})
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
789 次 |
| 最近记录: |