本篇基于技术栈 vue2 + vue-cli + webpack。
业务中分为测试环境和生产环境,对应 API 地址不同,我分别做了打包配置。
当前 vue 项目配置和之前的略有不同,记录一下打包上线配置。代码上传到服务器中,使用 nginx 代理。
按照环境模式区分
package.json中配置命令,其中--host可以在dev模式下,使用本机IP访问系统。
 | "scripts": {    "dev": "vue-cli-service serve --mode dev --host 0.0.0.0",    "serve": "vue-cli-service serve --mode serve",    "test": "vue-cli-service build --mode serve",    "prod":"vue-cli-service build --mode prod"  },
 
  | 
 
针对3个不同的环境,创建3个文件,这里定义在src/api/**中使用process.env.VUE_APP_INTERFACE_URL来获取当前环境下的API地址。
dev环境
根目录下新建.env.dev文件
 | NODE_ENV = 'development' VUE_APP_TITLE = 'development' VUE_APP_INTERFACE_URL="" /* 请求接口地址 */ VUE_APP_MOCK = true
 
  | 
 
dev环境若需要设置代理,vue.config.js中添加以下内容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
   | const { defineConfig } = require("@vue/cli-service"); const path = require("path");
  module.exports = defineConfig({   publicPath: process.env.NODE_ENV === "production" ? "/" : "/",   transpileDependencies: true,   lintOnSave: false,   devServer: {     port: 8080,     host: "127.0.0.1",     open: true,      headers: {       "Access-Control-Allow-Origin": "*",       "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",       "Access-Control-Allow-Headers":         "X-Requested-With, content-type, Authorization",     },     proxy: {       "/api": {         target: "http://***",         changeOrigin: true,         secure: false,         pathRewrite: { "^/api": "/api" },       },     },   }, });
 
  | 
 
test环境
根目录下新建.env.serve文件
 | NODE_ENV = 'server' VUE_APP_TITLE = 'server' VUE_APP_INTERFACE_URL="http://***:19991"
 
  | 
 
production环境
根目录下新建.env.prod文件
 | NODE_ENV='production' VUE_APP_TITLE='prod' VUE_APP_INTERFACE_URL="http://***:19999"
 
  | 
 
打包去除console
因为开发环境写了一些log,打包上线时为了更加干净需要去除。
安装插件
 | npm install babel-plugin-transform-remove-console --save-dev
 
  | 
 
在项目的babel.config.js的plugin中添加如下代码:
 | module.exports = {   presets: ["@vue/cli-plugin-babel/preset"],   plugins:[     ...proPlugins   ] };
 
  | 
 
打包到服务器指定目录下
如最终需要浏览器访问地址为http://***:port/demo/,就需要修改路径,已解决无法访问静态资源的问题。
修改vue.config.js中的地址:
 | module.exports = defineConfig({   publicPath: process.env.NODE_ENV === 'production' ? '/demo/' : '/', }
 
  | 
 
nginx中添加如下配置:
 | location /demo/ {   root /data/; //root   index index.html index.htm;   try_files $uri $uri/ /demo/; }
 
  | 
 
错误
