环境
vue 2.5.2、webpack 3.6.0、prerender-spa-plugin 3.4.0
遇到的问题
打包后出现的报错

相关代码
大部分能查到的资料都是添加chunks。但是在这里并没有生效,问题依然存在。
new HtmlWebpackPlugin({
filename: config.build.index,
template: 'index.html',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
},
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
chunks: ['manifest', 'vendor', 'app'],
chunksSortMode: 'dependency'
}),
// 在vue-cli生成的文件的基础上,只有下面这个才是我们要配置的
new PrerenderSPAPlugin({
// 生成文件的路径,也可以与webpakc打包的一致。
// 下面这句话非常重要!!!
// 这个目录只能有一级,如果目录层次大于一级,在生成的时候不会有任何错误提示,在预渲染的时候只会卡着不动。
staticDir: path.join(__dirname, '../dist'),
// 对应自己的路由文件,比如index有参数,就需要写成 /index/param1。
// routes: ['/', '/evaluation', '/case', '/mall', '/video', '/employ', '/expert'],
routes: ['/'],
// 这个很重要,如果没有配置这段,也不会进行预编译
renderer: new Renderer({
inject: {
foo: 'bar'
},
// 触发渲染的时间,用于获取数据后再保存渲染结果
// renderAfterTime: 10000,
// 是否打开浏览器,false 是打开。可用于 debug 检查渲染结果
headless: true,
// 在 main.js 中 document.dispatchEvent(new Event('render-event')),两者的事件名称要对应上。
renderAfterDocumentEvent: 'render-event'
})
}),
// keep module.id stable when vendor modules does not change
new webpack.HashedModuleIdsPlugin(),
// enable scope hoisting
new webpack.optimize.ModuleConcatenationPlugin(),
// extract webpack runtime and module manifest to its own file in order to
// prevent vendor hash from being updated whenever app bundle is updated
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
minChunks: Infinity
}),
// split vendor js into its own file
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks(module) {
// any required modules inside node_modules are extracted to vendor
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf(
path.join(__dirname, '../node_modules')
) === 0
)
}
}),
// This instance extracts shared chunks from code splitted chunks and bundles them
// in a separate chunk, similar to the vendor chunk
// see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk
new webpack.optimize.CommonsChunkPlugin({
name: 'app',
async: 'vendor-async',
children: true,
minChunks: 3
}),
分析

标红线的js。公共js在body里面。而页面js却在head头部上面。正确逻辑页面js应该在公共js的下方才能生效。这就导致了报错,直接点的解决方法就是删除head的js,或者手动移动到公共js下方。但显然不是我能接受的。
进一步分析,其实这个页面js的生成时由于路由懒加载而生成的分页js。
解决方案
只需要把关于首页的路由懒加载取消掉。就不会生成head里面的页面js文件。并且也能正常运行。

803




被折叠的 条评论
为什么被折叠?



