In the last week for some reason, my Vercel Hack stopped working. The variables were not importing as expected.
In case this does not work for you, here is the webpack version. I wonder if using webpack actually slows down the build process or not? Should it be avoided? Comment if you know please. I am thinking you should avoid any external dependencies when possible, but this makes using process.env
seemless.
Here are instructions with Angular Universal. I had to compile different results on Google, as I tried to simplify things that others seem to over complicate --- as usual. ( ͡° ͜ʖ ͡°)
Install Dependencies
npm i -D @angular-builders/custom-webpack
npm i -D @angular-builders/dev-server
npm i -D dotenv
Create custom-webpack.config.ts
Always use Typescript! This should be a rule for all JS developer companies. Put this in your root directory.
import { EnvironmentPlugin } from 'webpack';
import { config } from 'dotenv';
config();
module.exports = {
plugins: [
new EnvironmentPlugin([
'FIREBASE_API_DEV',
'FIREBASE_API_PROD'
])
]
}
Of course I am using a Firebase example here, as you can import it as a JSON file.
Edit Environment Files
environment.prod.ts
export const environment = {
production: true,
firebase: JSON.parse(process.env.FIREBASE_API_PROD as string)
};
If you are just importing a string, you don't need JSON.parse()
here. Do the same for all environment version files.
Edit Angular.json
Replace projects.architect.build.builder:
From:
@angular-devkit/build-angular:browser
To:
@angular-builders/custom-webpack:browser
Replace projects.architect.serve.builder:
From:
@angular-devkit/build-angular:dev-server
To:
@angular-builders/custom-webpack:dev-server
Replace projects.architect.test.builder:
From:
@angular-devkit/build-angular:karma
To:
@angular-builders/custom-webpack:karma
Replace projects.architect.server.builder:
From:
@angular-devkit/build-angular:server
To:
@angular-builders/custom-webpack:server
Add to:
projects.architect.server.options
projects.architect.build.options
projects.architect.test.options
"customWebpackConfig": {
"path": "./custom-webpack.config.ts"
},
Create Your .env File
Put your variables in your .env
file as usual:
FIREBASE_API_DEV={"apiKey":"..." ...}
FIREBASE_API_PROD={...}
And done. Here is my repository if you need an example.
NOTE: Remember to add .env
to your .gitignore
file.
J