LazyCodet

a

17:48:58 18/5/2024 - 0 views -
Programming

How to specify the .env file will be built in Frontend - npm run build


​Issue

​When I want to CI/CD my project, I hope when CI is processing, it uses the .env.prod file to build the assets instead of the .env file (for the development environment). So I found a solution for this so I want to share it with you.

​Get started

​Install the env-cmd package 

npm install --save-dev env-cmd

​Create a .env file (development)

VITE_ENVIRONMENT=development
Create a .env.prod (production)
VITE_ENVIRONMENT=production
​Create a file to use the environment variable
<script setup lang="ts">
const env = import.meta.env.VITE_ENVIRONMENT;
</script>
<template>
    <div>
        <h2>{{ env }}</h2>
    </div>
</template>
Package.json
"scripts": {
    "dev": "vite",
    "build": "vue-tsc && vite build",
    "build:prod": "env-cmd -f ./.env.prod npm run-script build"
  },
Usage

​Try to run this command:

npm run build

​You will see the import.meta.env.VITE_ENVIRONMENT => development

​Try to run this command:

npm run build:pro

You will see the import.meta.env.VITE_ENVIRONMENT => production

​Conclusion

In this guide, we've outlined a method to manage environment-specific variables in a Vue 3 project using the env-cmd package. By separating environment configurations into .env and .env.prod files, we can easily switch between development and production environments during CI/CD processes.

​References

​https://stackoverflow.com/a/57531118