首先查看配置文件,在webpack.config.server.js中入口配置错误:
1 在服务端webpack配置中入口文件写错为entry: path.join(__dirname, ‘…/client/client-entry.js’)
应该为entry: path.join(__dirname, ‘…/client/server-entry.js’)
2. 报错: Request failed with status code 404 没有找到该资源
位置:
try {
clientManifestResp =await axios.get("http://localhost:8000/vue-ssr-client-manifest.json")
} catch (error) {
console.log('aaaaa',error)
}
配置文件中资源开放在/public/下,所以资源访问url应为:
http://localhost:8000/public/vue-ssr-client-manifest.json
3 Error: vue-loader was used without the corresponding plugin. Make sure to include VueLoaderPlugin in your webpack config.
服务端配置文件中缺少vue-loader插件,配置vue-loader插件
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const plugins = [
new VueLoaderPlugin(),
]
4 TypeError: Cannot assign to read only property ‘exports’ of object ‘#Object’
报错原因: 新webpack不允许 import 和 module.exports 共存
import createApp from './create-app'
module.exports = () => {}
改为
import createApp from './create-app'
export default () => {}
5 ReferenceError: document is not defined
服务端渲染打包的配置中使用了mini-css-extract-plugin,导致server bundle中会使用到document,node环境中不存在window对象,所以报错。
解决方法:在服务端配置中不使用mini-css-extract-plugin,改为:
{
test: /\.styl(us)?$/,
use: [
'vue-style-loader',
{
loader: 'css-loader',
options: {
// modules: true, // 启用css模块
// localIdentName: '[path]-[name]-[hash:base64:5]', // 将css文件以指定文件名输出
camelCase: true
}
},
{
loader: 'postcss-loader',
options: {sourceMap: true}
},
'stylus-loader',
]
}
为什么会注释上方配置?
在渲染后的页面查看源码,使用module模式的css文件中,其中类名会被编译为一段哈希值。但在打包的css文件中的类名仍为为编译的类名,导致二者无法匹配,最终样式无法正常显示。
6 express解决请求/favicon.ico资源失败:使用serve-favicon
const favicon = require('serve-favicon')
app.use(favicon(path.join(__dirname, '../favicon.ico'))) //favicon.icon文件的路径
7 在依赖文件中,vue-meta版本为2.1.0
TypeError: Cannot set property console of #
由报错信息来看,修改控制台属性是不被允许的。
解决办法:降低版本为2.0.5
降低版本后,报错找不到node_modules/vue-meta/dist/vue-meta.esm.js,但是在查看node_modules时,存在这个路径的。所以有可能时降版本时出了问题。可以将node_modules文件删除,重新下载依赖。
关于版本兼容问题
8 关于express访问静态资源的方法
app.use('/public', express.static('public'))
此时,即可以从/public路径加载public目录中的文件。
9 资源打包后,访问5000端口,发现请求图片资源失败。在通过服务端渲染的网页的源码中,与其他静态资源请求路径相比较,图片的资源路径中缺少/public,因此,图片访问的路径是不正确的,我们需要在路径中加上/public
解决办法:在通用配置文件中,输出模块添加publicPath属性
output: {
filename: 'bundle.[hash:8].js',
path: path.resolve(__dirname, '../public'),
publicPath: '/public/'
}
参考文档