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

零下一度
零下一度 原创
2017-06-25 09:35:32 3431浏览

坑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: '//m.sbmmt.com/m/', 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官方文档:

以上就是vue项目实战中遇到的坑以及解决方法的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。