Reputation: 25
How to deploy my angular application in Vercel with my environment variables.
Here's my GitHub repo of this project = https://github.com/TarunUM/clipped
I've tried using 'dotenv' in my environment and the application run perfectly but when I tried to build it from 'ng build' but it threw errors like : (https://i.sstatic.net/GMqCX.jpg)
Upvotes: 0
Views: 1276
Reputation: 21
In order to access environment variables, we have to use process.env.API_KEY. But we cannot simply just run this snippet on browser side code. So, in order to solve this issue I have created a script which basically writes content to environment.ts
file.
const setEnv = () => {
const fs = require('fs');
const writeFile = fs.writeFile;
const targetPath = './src/environments/environment.ts';
const colors = require('colors');
require('dotenv').config({
path: 'src/environments/.env'
});
// `environment.ts` file structure
const envConfigFile = `export const environment = {
apiKey: '${**process.env.API_KEY**}',
production: true,
};
`;
writeFile(targetPath, envConfigFile, (err) => {
if (err) {
console.error(err);
throw err;
}
});
setEnv();
And then don't forget to add this script to your package.json file. In my case, I am working with Nx workspace so it looks something like this.
"scripts": {
"start": "nx serve",
"build": "node config.js && nx build",
"test": "nx test",
},
Now, you can simply run npm run build
which will override the content of your environment.ts file.
enter image description here
Hope this helps! Good day
Upvotes: 2