1.第一种方式,nginx处理静态文件,遇到api接口做反向代理
//vue开发中,vue.config.js配置如下
proxy: {
'/api': {
target: 'http://127.0.0.1:7001',
ws: true,
changeOrigin: true,
pathRewrite: {
"^/api": ""
}
},
},
//vue正常打包到dist目录,放到nginx上,配置如下
gzip on;
gzip_static on; // 开启静态资源压缩,需要webpack配置打包压缩插件,见底部compression-webpack-plugin配置
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
try_files $uri $uri/ /index.html; // 启用history模式
add_header Cache-Control "no-cache"; // 协商缓存,304,优先使用ETag协商模式
}
location /api/ {
proxy_pass http://127.0.0.1:7001/;
}
}
//这里特别注意,api前后有/,7001后面有/
2.第二种方式,EggJS给Vue单页面提供静态服务
1. config/plugin.js开启静态插件
exports.static={
enable: true,
}
2. config/config.default.js中配置静态文件存放的文件夹
config.assets = {
publicPath: '/public/',
}
3. 配置路由,访问 /时,去请求index控制器的get方法
router.get('/', controller.index.get);
4. 配置controller,读取index.html文件, 以html形式返回给请求方
const fs = require('fs')
const path = require('path')
async get() {
let { ctx } = this;
ctx.response.type = 'html'
ctx.body = fs.readFileSync(path.resolve(__dirname, '../public/index.html'))
}
5. 前端修改打包输出配置
publicPath: '../public',
outputDir: 'dist',
如上操作,把打包后的dist目录内容,复制到egg/app/public目录下,即可正常打开静态文件。
如果需要正常可以访问接口:
1.需要把跨域部分devServer注释,
2.封装axios时的baseURL注释掉,
即可正常访问接口
如上,完成eggjs部署。
compression-webpack-plugin插件的使用
该插件可以压缩vue静态资源,生成gz结尾的文件(多生成一份gz文件)
如果不压缩,直接使用nginx的gzip on;属于服务器动态压缩,浪费性能
这里webpack打包压缩,会生成静态资源的gz包,放到服务器上以后,开启nginx的gzip_static on;属于静态压缩,不浪费服务器资源
我们通常使用这个方案,虽然包稍微大了一点,但服务器请求速度杠杠的
npm install compression-webpack-plugin --save-dev
高版本可能会有问题,我这里踩坑后制定使用了5.0.1版本
下面是在vue.config.js里配置webpack
const CompressionPlugin = require('compression-webpack-plugin')
const compress = new CompressionPlugin({
filename: info => {
return `${info.path}.gz${info.query}`
},
algorithm: 'gzip',
threshold: 10240, //这里是大于10KB的就压缩
test: new RegExp(
'\\.(' + ['js'].join('|') +
')$'
),
minRatio: 1, // 只有压缩率小于这个值的资源才会被处理
deleteOriginalAssets: false // 删除原文件
})
configureWebpack: {
name: name,
resolve: {
alias: {
'@': resolve('src')
}
},
externals: {
'axios': 'axios',
'dayjs': 'dayjs',
'crypto-js': 'CryptoJS',
'vue': 'Vue',
'vue-router': 'VueRouter',
'vuex': 'Vuex',
'element-ui': 'ELEMENT'
},
plugins: [compress]
},
网友评论