• vue cli 打包、生产环境http-proxy-middleware代理


    结构树

    版本

    1、创建vue.config.js

    1. const path = require('path');
    2. const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
    3. //压缩
    4. const CompressionWebpackPlugin = require('compression-webpack-plugin')
    5. const isProduction = process.env.NODE_ENV !== 'development';
    6. module.exports = {
    7. // 将 examples 目录添加为新的页面
    8. pages: {
    9. index: {
    10. // page 的入口
    11. entry: process.env.NODE_ENV === 'production' ? 'src/main-prod.js' : 'src/main.js',
    12. // 模板来源
    13. template: 'public/index.html',
    14. // 输出文件名
    15. filename: 'index.html'
    16. }
    17. },
    18. runtimeCompiler: true,
    19. publicPath: "./", // 官方要求修改路径在这里做更改,默认是根目录下,可以自行配置
    20. outputDir: 'dist', //标识是打包哪个文件
    21. productionSourceMap: false,
    22. configureWebpack: config => {
    23. if (isProduction) {
    24. //移除代码中的打印
    25. config.plugins.push(
    26. new UglifyJsPlugin({
    27. uglifyOptions: {
    28. output: {
    29. comments: false, // 去掉注释
    30. },
    31. warnings: false,
    32. compress: {
    33. drop_console: true,
    34. drop_debugger: false,
    35. pure_funcs: ['console.log']//移除console
    36. }
    37. }
    38. })
    39. )
    40. //压缩大于200k的文件
    41. config.plugins.push(
    42. new CompressionWebpackPlugin({
    43. filename: '[path][base].gz',
    44. algorithm: 'gzip',
    45. // test: /\.js$|\.html$|\.json$|\.css/,
    46. test: /\.js$|\.json$|\.css/,
    47. threshold: 204800, // 只有大小大于该值的资源会被处理
    48. minRatio: 0.8, // 只有压缩率小于这个值的资源才会被处理
    49. // deleteOriginalAssets: true // 删除原文件
    50. }))
    51. }
    52. console.log("------------------------------" + isProduction)
    53. },
    54. chainWebpack: config => {
    55. // 发布模式 优化首次加载 采用本地cdn(若需要更多优化可自行添加)
    56. config.when(process.env.NODE_ENV === 'production', config => {
    57. config.set('externals', {
    58. axios: 'axios',
    59. 'vue-router': 'VueRouter',
    60. })
    61. })
    62. },
    63. devServer: {
    64. proxy: {
    65. '/config': {
    66. target: 'http://xxx.xxx.xx.xxx:xxx',//代理地址,这里设置的地址会代替axios中设置的baseURL
    67. //changeOrigin: true,// 如果接口跨域,需要进行这个参数配置
    68. //ws: true, // proxy websockets
    69. //pathRewrite方法重写url
    70. pathRewrite: {
    71. '^/config': '/config'
    72. //pathRewrite: {'^/api': '/'} 重写之后url为
    73. //pathRewrite: {'^/api': '/api'} 重写之后url为 /api/xxxx
    74. }
    75. }
    76. , '/guacamole': {
    77. target: 'ws://xxx.xxx.xx.xxx:xxx',
    78. pathRewrite: {
    79. '^/guacamole': '/guacamole'
    80. }
    81. },
    82. }
    83. },
    84. css: {
    85. loaderOptions: {
    86. less: {
    87. lessOptions: {
    88. modifyVars: {},
    89. javascriptEnabled: true,
    90. },
    91. },
    92. },
    93. },
    94. }

    如果采用了本地cdn则index.html

    1. <% if (process.env.NODE_ENV==='production' ) { %>
    2. <script src="./static/axios.0.21.1.min.js">script>
    3. <script src="./static/vue-router.min.js">script>
    4. <% } %>

    2、创建ecosystem.config.js

    1. module.exports = {
    2. apps: [{
    3. // 测试环境
    4. name: "test",
    5. script: "himdcs.js",
    6. env: {
    7. "NODE_ENV": "test"
    8. }
    9. }
    10. ]
    11. }

    3、创建himdcs.js

    1. const express = require('express'); //npm下载并引入express模块 npm -express -D
    2. const proxy = require('http-proxy-middleware');
    3. // 导入压缩包
    4. const compression = require('compression');
    5. const cors = require('cors');
    6. const app = express();
    7. app.use(cors())
    8. // 启用中间件 要写在静态资源托管之前 用于静态文件压缩包
    9. app.use(compression());
    10. app.use(express.static('./dist')) // ./dist 为vue打包后dist文件夹的路径
    11. app.listen(1897,function(err){ //8080 想要监听项目的端口号
    12. if(err){
    13. console.log(err)
    14. }else {
    15. console.log('项目启动成功')
    16. }
    17. })
    18. //用于服务部署时的代理
    19. app.use(
    20. ['*/config/*'],
    21. proxy.createProxyMiddleware({
    22. target:'http://xxx.xxx.xx.xxx:xxxx', // 服务器api地址目录
    23. changeOrigin: true,
    24. secure: false,
    25. xfwd:true,//添加x-forward请求头
    26. pathRewrite: {
    27. '/config': '/config' // rewrite path
    28. }
    29. }));
    30. //websocket
    31. app.use(
    32. ['/beat'],
    33. proxy.createProxyMiddleware({
    34. target:'ws://xxx.xxx.xx.xxx:xxxx', // 服务器api地址目录
    35. changeOrigin: true,
    36. ws: true,
    37. xfwd:true,
    38. pathRewrite: {
    39. '/beat': '/beat' // rewrite path
    40. }
    41. }));

    4、修改package.json

    1. {
    2. "name": "",
    3. "version": "3.0.0",
    4. "private": true,
    5. "scripts": {
    6. "dev": "vue-cli-service serve --mode development",
    7. "prod": "vue-cli-service build --mode production",
    8. "serve": "vue-cli-service serve",
    9. "build": "vue-cli-service build --mode production",
    10. "lint": "vue-cli-service lint"
    11. },
    12. "dependencies": {...}
    13. ...
    14. }

    5、部署到docker

    1. FROM keymetrics/pm2:latest-alpine
    2. # Bundle APP files
    3. RUN mkdir -p /home/
    4. WORKDIR /home/
    5. #COPY src src/
    6. #COPY package.json .
    7. COPY . /home/
    8. # Install app dependencies
    9. ENV NPM_CONFIG_LOGLEVEL warn
    10. # Show current folder structure in logs
    11. #RUN ls -al -R
    12. CMD pm2-docker start ecosystem.config.js --only $NODE_ENV --watch

    6、http-proxy-middleware参数说明

    option.target:url字符串将与url模块解析
    option.forward:url字符串将与url模块解析
    option.target:传递给http(s)请求的对象(参阅Node https代理和http代理对象)
    option.ssl:传递给https.createServer()的对象
    option.ws:true / false,如果你想要代理websockets
    option.xfwd:true / false,添加x-forward请求头
    option.secure:true / false,如果你想要验证SSL证书
    option.toProxy:true / false,将绝对URL作为​​path​​(对代理使用代理时很有用)
    option.prependPath:true / false,默认:true-指定是否要将目标的路径预置到代理路径
    option.ignorePath:true / false,默认:false-指定是否要忽略传入请求的代理路径(注意:如果需要,您将必须附加/手动)。
    option.localAddress:用于传出连接的本地接口字符串
    option.changeOrigin:true / false,默认值:false - 将主机头的源更改为目标URL
    option.auth:基本认证,即“用户:密码”来计算授权头。
    option.hostRewrite:重写(301/302/307/308)重定向的位置主机名。
    option.autoRewrite:根据请求的主机/端口重写(301/302/307/308)重定向的位置主机/端口。默认值:false。
    option.protocolRewrite:重写位置协议(301/302/307/308)重定向到’http’或’https’。默认值:null。
    option.cookieDomainRewrite:重写set-cookie标头的域。可能的值:
    -​​​false​​​(默认):禁止重写​​cookie​​​
    - 字符串:新域名,比如说​​​cookieDomainRewrite:"new.domain"​​​。使用​​cookieDomainRewrite:""​​​删除域名。
    - 对象:域名到新域名的映射,用”*”匹配所有域名。
    举个栗子:保持一个域名不变,重写一个域名并且删除其他的:
    ​​
    cookieDomainRewrite: {
    "unchanged.domain": "unchanged.domain",
    "old.domain": "new.domain",
    "*": ""
    }

    option.headers:对象,添加请求头。(比如:​​{host:'www.example.org'}​​)
    option.proxyTimeout:超时时间(毫秒)当代理接收不到目标服务器的返回
     

  • 相关阅读:
    拦截器与过滤器的区别
    全流量分析应用运行和访问情况
    用DIV+CSS技术设计的明星个人网站制作(基于HTML+CSS+JavaScript制作明星彭于晏网页)
    苍穹外卖-day12 - 工作台 - Apache POI - 导出运营数据Excel报表
    Linksys RE7000 “AccessControlList ”命令执行漏洞(CVE-2024-25852 )
    【软考 系统架构设计师】计算机组成与体系结构③ 存储管理
    redis配制redis-static-server
    注解的知识和应用案例
    线上动态解析protobuf文件,实现动态热更新
    4、Java——循环案例代码详解(1)
  • 原文地址:https://blog.csdn.net/qq_34533703/article/details/132859622