在 Vue.js 中构建期间传递要由 .env.[mode] 文件使用的参数(命令行) [英] Pass an argument (command line) to be used by an .env.[mode] file, during build in Vue.js
问题描述
目标:
传递要在构建时使用的参数,以便能够在我的 .env.production 文件中使用它(或者如果不可能的话,可以让我将其用作环境变量).
Goal:
Pass an argument to be used during build time, to be able to use it in my .env.production file (or something that lets me use it as an environment variable if that's not possible).
.env.production 文件:
.env.production file:
VUE_APP_CLIENT_ID=00-should-be-using-what-was-passed-by-command-00
Docker 文件:
#Inside my docker file
RUN npm run build #I need to pass the argument here
我的 package.json 脚本是:
My package.json scripts are:
"scripts": {
"serve": "vue-cli-service serve --mode development",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"test:unit": "vue-cli-service test:unit"
},
为什么:
OBS:我确实使用 webpack,它已经由 vue-cli 配置
我知道我可以配置不同的 .env 文件和模式,但我需要能够注入"或在我的 .env.production 文件中有一个动态变量,因为有时我为不同的服务器构建生产.
我可以创建更多文件,这可以解决我的问题,但我想要更实用的东西.
Why:
OBS: I do use webpack, it's configured already by the vue-cli
I know I can configure different .env files and modes, but I need to be able to 'inject' or have a dynamic variable in my .env.production file as sometimes I build for production for different servers.
I could create even more files and that'd solve my problem but I want something more practical that that.
上下文:
我正在使用 Docker 和 Auth0,实际上我使用的是 VUE_APP_CLIENT_ID
环境变量,该变量定义了它是否要为请求点击,我已经有两个不同的 VUE_APP_CLIENT_ID
定义(一个在 .env.development 一个在 .env.production 上)问题是我需要在两个不同的服务器中部署完全相同的服务器,每个服务器在生产中针对不同的 client_id.
Context:
I'm using Docker and Auth0, and I'm actually using a VUE_APP_CLIENT_ID
env variable that defines were it's going to tap for a request, I already have two different VUE_APP_CLIENT_ID
definitions (one on .env.development one on .env.production) the thing is that I need to deploy the exact same up just in two different servers that each one target different client_id on production.
工具:
Docker、docker-compose、Vue.js、vue-cli 3、npm
Tools:
Docker, docker-compose, Vue.js, vue-cli 3, npm
操作系统:
Ubuntu 16.04
OS:
Ubuntu 16.04
推荐答案
- 解决方案 1:
由于process.env
暴露了所有的环境变量,所以你可以运行
Since the process.env
expose all environment variables, so you can run
export MYCUSTOMENV=foo &&npm run build
并在您想要的任何地方使用 process.env.MYCUSTOMENV
.
and the use process.env.MYCUSTOMENV
in anywhere you want.
来自 vue 文档:只有以 VUE_APP_ 开头的变量才会被静态嵌入到客户端包中.
From vue doc: Only variables that start with VUE_APP_ will be statically embedded into the client bundle.
- 解决方案 2
使用 process.argv
获取所有参数,并过滤您想要的内容:
Use process.argv
to get all argument, and filter what you want:
npm run build a=b foo
process.argv.forEach((val, index) => {
console.log(`${index}: ${val}`);
});
输出:
0: /usr/local/bin/node
1: /Users/tzp/xxx/vue-cli-service
2: build
3: a=b
4: foo
这篇关于在 Vue.js 中构建期间传递要由 .env.[mode] 文件使用的参数(命令行)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!