How to use DotEnv with Ionic v5?

I happen to be using Ionic-Vue but I imagine the situation is the same for all users. I have not been able to figure out, what is the build system under the hood when we use ionic serve? Is Webpack called? Is it handled entirely by Capacitor?

Problem:
I am unable to use dotenv as the fs module is not found, given this is not a “node” application, but a front end application. I believe dotenv is still frequently used is projects such as these but with a dev and production set of environment variables that are injected by webpack.

It looks as though on a typical Vue 3 application .env files are supported “natively”, but that does not appear to be working for me at least.

what are you trying to do with .env ? I have it working with code I just posted yesterday

VUE_APP_FIREBASE_PROJECT_ID=XXX-XXX-XXX

Then in my code

const db = firebase
  .initializeApp({ projectId: process.env.VUE_APP_FIREBASE_PROJECT_ID })
  .firestore();
1 Like

I am attempting something very similar to this example. I have removed dotenv from my project (which I originally installed thinking it was needed), and reinstalled my packages just in case.

I have a .env file in the root of my project:

API_URL=api.x.com

Then within src/main.ts I have:

console.log("env: " + process.env.API_URL)

Which returns undefined.

I can actually share the Github URL this time, the project is now public: https://github.com/KyleTryon/Sample-ZoomFood-FrontEnd

ionic serve is just calling the vue cli service under the hood, so npm run start and ionic serve should be doing the same exact thing.

2 Likes

see the doc… you have to start your variable with VUE_APP_

4 Likes

Very sorry about that, did not realize the VUE_APP was a requirement and not an example. And thank you @mhartington that also cleared up a major question I had.

Thank you @aaronksaunders I have just validated that this is working :+1:. Appreciate the help and patience.

2 Likes

Thank you Aaron! You’re a lifesaver.

Had same Issue and VUE_APP solved it thanks