vue-cli4项目打包后使用nginx部署到服务器打开页面为空白的问题
控制台报错
// 报错
chunk-elementUI.d05b1787.js:1 Uncaught SyntaxError: Unexpected token '<'
// 警告
Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://xxx.com/static/css/app.7d4e3231.css".
复制代码
我寻思是vueCli4和webpack配置问题或者是nginx配置问题。
vue项目中配置webpack
我的vue.config.js文件配置如下
'use strict'
const path = require('path')
const defaultSettings = require('./src/settings.js')
function resolve (dir) {
return path.join(__dirname, dir)
}
const name = defaultSettings.title || 'vue Admin Template' // page title
module.exports = {
publicPath: './',
outputDir: 'dist',
assetsDir: 'static',
// lintOnSave: process.env.NODE_ENV === 'development',
lintOnSave: false,
productionSourceMap: false,
devServer: {
// port: port,
open: true,
overlay: {
warnings: false,
errors: true
}
},
configureWebpack: {
// provide the app's title in webpack's name field, so that
// it can be accessed in index.html to inject the correct title.
name: name,
resolve: {
alias: {
'@': resolve('src')
}
}
},
......不重要信息省略
}
}
复制代码
nginx中的nginx.conf文件配置如下
worker_processes 2;
events {
#use epoll;
worker_connections 2048;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
server {
listen 80;
server_name xxx.com;
location / {
root html;
index index.html;
try_files $uri $uri/ /index.html; #后端支持 hash 变为 history 的关键代码
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
}
location /manager {
alias html/manager/;
index index.html;
try_files $uri $uri/ /manager/index.html; #后端支持 hash 变为 history 的关键代码
}
location /invoice {
alias html/invoice;
index index.html;
}
location /status {
stub_status on;
access_log off;
}
}
}
}
复制代码
测试方案1:
文件里面有两个assetsPublicPath属性,更改第一个,也就是更改build里面的assetsPublicPath属性:
结果:这应该是低版本的vueCli,现在版本没有assetsPublicPath字段。
参考链接:www.cnblogs.com/facefront/p…
测试方案2:
- 第一个解决方法是把mode改成history这个问题就会消失\
- 第二个解决方法是publicPath设置成’/’,不能是’./’
结果:测试了无效。
参考链接:blog.csdn.net/yyj108317/a…
测试方案3:
经过问题排查发现,vue-cli默认build后的文件名格式为js/[name].[chunkhash].js
,每次npm run build
后有改动的文件hash值都会改变,上传后Nginx无法找到最新上传的文件,所以返回了默认index.html
里的内容,我们的文件后缀名是.js
自然无法识别<html>
这种标签符号,导致console抛出Uncaught SyntaxError:Unexpected token <
,我尝试修改build/webpack.prod.conf.js
output输出文件名格式,目前问题已得到解决
结果:现在版本的vueCli4好像也不支持output字段,所以没有修改。但是提供了一个好思路。是因为nginx最新上传的文件没有被浏览器正确识别,浏览器用的是没有更新的旧文件。hash值不同所以导致报错。于是呢,我将浏览器的缓存全部清除了,发现就可以了,没有报错了。呜呜呜搞了大半天。
参考链接:blog.csdn.net/weixin_3399…
测试方案4:
结果:原本就有这个配置。
心得
webpack和nginx需要深入学习。半斤八两的很浪费时间。
webpack官网链接:webpack.docschina.org/concepts/