
1.项目新建配置文件

# 在vue项目模块中,新建两个文件 .env.prod (生产环境配置) .env.dev (开发环境配置)

NODE_ENV=production VUE_APP_SERVER=http://xxxx.com(生产的后端域名)
NODE_ENV=development VUE_APP_SERVER=http://127.0.0.1:9000(本机的后端地址)
NODE_ENV(node environment) 用来表示构建项目的当前环境 自定义多环境变量必须以VUE_APP开头
2.测试
main.js中添加 console.log("环境:",process.env.NODE_ENV); NODE_ENV对应配置文件的变量

启动项目查看前端输出 本机启动项目默认是开发环境

3.配置启动脚本
package.json中添加/替换 "serve-dev": "vue-cli-service serve --mode dev", "serve-prod": "vue-cli-service serve --mode prod",

刷新脚本 更换脚本启动器命令


4.替换URL
替换前 'http://127.0.0.1:9000/business/admin/chapter/delete/'

替换后 process.env.VUE_APP_SERVER+'/business/admin/chapter/delete/'

再次启动测试原有的功能即可
5.npm run build 时也可以指定env
// build时,会把.env.dev.js内容打包到工程中 npm run build -- --mode dev // build时,会把.env.prod.js内容打包到工程中 npm run build -- --mode prod
DockerFile中 build Vue代码时也可以用上面命令打包
# build stage FROM node:14.17.6-alpine as build-stage ARG MODE=dev WORKDIR /app COPY package*.json ./ RUN npm install COPY . . //这里指定配置文件。 # see also https://stackoverflow.com/q/50772662/2497876 RUN npm run build -- --mode ${MODE} # production stage FROM nginx:1.17.9-alpine as production-stage # support running as arbitrary user which belogs to the root group RUN chmod g+rwx /var/cache/nginx /var/run /var/log/nginx RUN chgrp -R root /var/cache/nginx # users are not allowed to listen on priviliged ports RUN sed -i.bak 's/listen\(.*\)80;/listen 8081;/' /etc/nginx/conf.d/default.conf EXPOSE 8081 # comment user directive as master process is run as user in OpenShift anyhow RUN sed -i.bak 's/^user/#user/' /etc/nginx/nginx.conf RUN addgroup nginx root USER nginx COPY --from=build-stage /app/dist /usr/share/nginx/html # COPY prod_nginx.conf /etc/nginx/nginx.conf CMD ["nginx", "-g", "daemon off;"]