Pass an argument (command line) to be used by an .env.[mode] file, during build in Vue.js
Asked Answered
M

1

9

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 file:

VUE_APP_CLIENT_ID=00-should-be-using-what-was-passed-by-command-00

Docker file:

#Inside my docker file
RUN npm run build #I need to pass the argument here

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"
 },

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.

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.

Tools:
Docker, docker-compose, Vue.js, vue-cli 3, npm

OS:
Ubuntu 16.04

Mailand answered 18/2, 2019 at 10:54 Comment(0)
V
13
  1. Solution-1:

Since the process.env expose all environment variables, so you can run

export MYCUSTOMENV=foo && npm run build

and the use process.env.MYCUSTOMENV in anywhere you want.

From vue doc: Only variables that start with VUE_APP_ will be statically embedded into the client bundle.

  1. Solution-2

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}`);
});

output:

0: /usr/local/bin/node
1: /Users/tzp/xxx/vue-cli-service
2: build
3: a=b
4: foo
Vibes answered 18/2, 2019 at 12:46 Comment(1)
that's such a clear and nice solution, I already had a VUE_APP_CLIENT_ID that I was using in my code, I just commented it from my.env file, went to my Docker file, replaced it with your line and voilà, problem solved , thanks!Mailand

© 2022 - 2024 — McMap. All rights reserved.