坑1. 用webpack打包后访问index.html出现资源加载404问题
解决方案:config中index.js中,build对象中的assetsPublicPath属性的层级需要由‘/’ 调整为'./'
1 build: {
2 env: require('./prod.env'),
3 index: path.resolve(__dirname, '../dist/index.html'),
4 assetsRoot: path.resolve(__dirname, '../dist'),
5 assetsSubDirectory: 'static',
6 assetsPublicPath: './',
7 productionSourceMap: false,
12 productionGzip: false,
13 productionGzipExtensions: ['js', 'css'],
18 bundleAnalyzerReport: process.env.npm_config_report
19 }dev: {
env: require('./dev.env'),
port: 8080,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
// CSS Sourcemaps off by default because relative paths are "buggy"
// with this option, according to the CSS-Loader README
// (https://github.com/webpack/css-loader#sourcemaps)
// In our experience, they generally work as expected,
// just be aware of this issue when enabling this option.
cssSourceMap: false
} 原因:
开发环境的static文件夹是基于根目录的,所以直接用‘/’ 。例如这种格式:http://localhost:8080/static/img/logo.png。
大家应该都知道,webpack打包会自动把static文件夹打包进去,默认会生成一个dist文件夹作为生产环境文件的根目录,在dist里面才会生成static文件夹。因此生成的格式应该为http://localhost:8080/dist/static/img/logo.png。并不是基于根目录,所以 ‘/’ 肯定是找不到对应资源的。
介绍一下这几个属性的含义:
assetsRoot: webpack输出的目标文件夹路径
assetsSubDirectory: webpack编译输出的二级文件夹
assetsPublicPath: webpack编译输出的发布路径,比如:www.woshichihuo.com/eat 中的 /eat就是这个路径
坑2. 用webpack打包后本地访问index.html出现白屏,资源加载正常
解决方案:路由设置mode不要设置为history模式,默认还是hash。router文件夹下index.js文件中。
const router = new Router({
// mode: 'history',
routes: [
index,
home
]
}) 如果需要history模式,请参考vue-router官方文档: https://router.vuejs.org/zh-cn/essentials/history-mode.html