vue cli搭建的项目,在本地测试调试都OK,运行npm run dev之后运行正常,今天放到服务器上跑,结果RD说找不到打包后的静态资源,浏览器控制台错误代码404
问了RD,因为服务器上线方式的调整,不会指定具体项目路径因此,https://bigdata.yiche.com/static/css/app.149f36018149fcbe537f02cafdc6f047.css 这个文件找不到,看看我们正常打包好的目录:
正确的访问路径是:https://bigdata.yiche.com/deploy/static/css/app.149f36018149fcbe537f02cafdc6f047
config/index.js配置如图:
思来想去之前打包好的文件直接扔到nginx就可以使用,实在不清楚原因。于是找到我们的美女组长姐姐来帮忙,分分钟改了config/index.js下的几行代码,如图:
这里需要注意assetsPublicPath:'/deploy/' 末尾的斜杠一定要加,不然部分js打包后会出现https://bigdata.yiche.com/deploystatic/css/app.149f36018149fcbe537f02cafdc6f047这样的情况。
看下打包好的目录,对比之后会发现多了一层deploy目录,这个多出来的路径是index和assetsRoot这两个设置决定的
而assetsPublicPath则是确定打包后的文件引用路径:看看打包后的index.html文件的js和css资源的引用路径:
对比之前默认配置的路径:
好了再放到服务器上,问题解决了。
问题总结:
原因是服务器没有指定项目目录,因此需要在打包时对打包文件添加访问的项目名称,所以在配置打包路径是要加上项目名称,下面是vue cli默认webpack config/index.js的配置解释
var path = require('path') 2 3 module.exports = { 4 build: { // production 环境 5 env: require('./prod.env'), // 使用 config/prod.env.js 中定义的编译环境 6 index: path.resolve(__dirname, '../dist/index.html'), // 编译输入的 index.html 文件 7 assetsRoot: path.resolve(__dirname, '../dist'), // 编译输出的静态资源路径 8 assetsSubDirectory: 'static', // 编译输出的二级目录 9 assetsPublicPath: '/', // 编译发布的根目录,可配置为资源服务器域名或 CDN 域名 10 productionSourceMap: true, // 是否开启 cssSourceMap 11 // Gzip off by default as many popular static hosts such as 12 // Surge or Netlify already gzip all static assets for you. 13 // Before setting to `true`, make sure to: 14 // npm install --save-dev compression-webpack-plugin 15 productionGzip: false, // 是否开启 gzip 16 productionGzipExtensions: ['js', 'css'] // 需要使用 gzip 压缩的文件扩展名 17 }, 18 dev: { // dev 环境 19 env: require('./dev.env'), // 使用 config/dev.env.js 中定义的编译环境 20 port: 8080, // 运行测试页面的端口 21 assetsSubDirectory: 'static', // 编译输出的二级目录 22 assetsPublicPath: '/', // 编译发布的根目录,可配置为资源服务器域名或 CDN 域名 23 proxyTable: {}, // 需要 proxyTable 代理的接口(可跨域) 24 // CSS Sourcemaps off by default because relative paths are "buggy" 25 // with this option, according to the CSS-Loader README 26 // (https://github.com/webpack/css-loader#sourcemaps) 27 // In our experience, they generally work as expected, 28 // just be aware of this issue when enabling this option. 29 cssSourceMap: false // 是否开启 cssSourceMap 30 } 31 }