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
This is a quick tutorial on how to create and access environment variables in Vue 3 with a dotenv ( . env ) file. Vue 3 apps built with Vite support dotenv environment variables out of the box, so all you need to do is add a . env file to the root folder of your Vue project.
You can access the binary directly as vue-cli-service in npm scripts, or as ./node_modules/. bin/vue-cli-service from the terminal. You can run scripts with additional features using the GUI with the vue ui command.
env file is placed at the base of the project directory. Project directory can be explicitly defined with the --file option or COMPOSE_FILE environment variable.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With