当前位置 主页 > 服务器问题 > nginx问题汇总 >

    vue填坑之webpack run build 静态资源找不到的解决方法

    栏目:nginx问题汇总 时间:2018-11-18 16:46

    今天小编就为大家分享一篇vue填坑之webpack run build 静态资源找不到的解决方法。具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

    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')module.exports = { build: { // production 环境 env: require('./prod.env'), // 使用 config/prod.env.js 中定义的编译环境 index: path.resolve(__dirname, '../dist/index.html'), // 编译输入的 index.html 文件 assetsRoot: path.resolve(__dirname, '../dist'), // 编译输出的静态资源路径 assetsSubDirectory: 'static', // 编译输出的二级目录 assetsPublicPath: '/', // 编译发布的根目录,可配置为资源服务器域名或 CDN 域名 productionSourceMap: true, // 是否开启 cssSourceMap // Gzip off by default as many popular static hosts such as // Surge or Netlify already gzip all static assets for you. // Before setting to `true`, make sure to: // npm install --save-dev compression-webpack-plugin productionGzip: false, // 是否开启 gzip productionGzipExtensions: ['js', 'css'] // 需要使用 gzip 压缩的文件扩展名 }, dev: { // dev 环境 env: require('./dev.env'), // 使用 config/dev.env.js 中定义的编译环境 port: 8080, // 运行测试页面的端口 assetsSubDirectory: 'static', // 编译输出的二级目录 assetsPublicPath: '/', // 编译发布的根目录,可配置为资源服务器域名或 CDN 域名 proxyTable: {}, // 需要 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 // 是否开启 cssSourceMap }}