您好,欢迎来到五一七教育网。
搜索
您的当前位置:首页vue项目实战中遇到的坑以及解决方法

vue项目实战中遇到的坑以及解决方法

来源:五一七教育网


坑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_report19 }
 1 dev: { 2 env: require('./dev.env'), 3 port: 8080, 4 autoOpenBrowser: true, 5 assetsSubDirectory: 'static', 6 assetsPublicPath: '/', 7 proxyTable: {}, 8 // CSS Sourcemaps off by default because relative paths are "buggy" 9 // with this option, according to the CSS-Loader README10 // ()11 // In our experience, they generally work as expected,12 // just be aware of this issue when enabling this option.13 cssSourceMap: false14 }

原因:

开发环境的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文件中。

1 const router = new Router({2 // mode: 'history',3 routes: [4 index,5 home6 ]7 })

如果需要history模式,请参考vue-router官方文档:

Copyright © 2019- 517ttc.cn 版权所有 赣ICP备2024042791号-8

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务