您好,欢迎访问一九零五行业门户网

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官方文档:
以上就是vue项目实战中遇到的坑以及解决方法的详细内容。
其它类似信息

推荐信息