How-to: Use different environment variables for production and development with ionic 3

Create 2 configuration files with environment variables in folder src/config: config.dev.ts and config.prod.ts


Update: For Ionic < 3.7

Override 2 configuration files provided by @ionic/app-scripts package: optimization.config.js and webpack.config.js

Notify ionic to use these overridden files by adding links to them to package.json


Update: For Ionic >= 3.7

Override webpack.config.js, provided by @ionic/app-scripts package.

Notify ionic to use overridden file by adding link to package.json


Instruct TypeScript to use custom alias for a module by editing tsconfig.json

Finally, use your environment variables

19 thoughts on “How-to: Use different environment variables for production and development with ionic 3”

  1. Thanks a lot for sharing this. Was really helpful to make my setup work.
    The only downside I found is when I have an environement that is prod-like, meaning using the –prod flag to build but some other env vars than prod, the ones from prod would get inline instead of the prod-like one.

    I guess in the early stages of the prod build that is something replacing the paths based on the tsconfig which defaults to the prod env file and is not based on the build env.

    Not sure if this makes sense to you.
    TL;DR: if you base your env on something else than the IONIC_ENV to have more than 2 envs, this won’t work for the prod builds.

    Let me know if can think of a solution for that or know which build step is replacing the files based on the tsconfig.

  2. did not work for me..
    I always got the dev environment when I use “ionic cordova run android” or “ionic cordova run android -prod”

    any helps ?
    Thanks

  3. Thanks a lot for this article, it works perfectly.
    For previous comments, try this:
    ionic cordova run android –prod

  4. Hi, I am getting this error when I run –prod: Error: Uncaught (in promise): Error: Cannot find module “@environment”.

    But I don’t get this error in dev. I have checked that the path correctly resolves in the webpack.config, and that the @environment is added to the typescript config. Any suggestions. I was using the example for ionic > 3.7

  5. Won’t the below line in tsconfig.json force the environment to prod always?

    “@environment”: [“config/config.prod”]

  6. For those having TS errors. I had to add a wildcard to includes to ensure TSC compiled all config files (otherwise only .prod seems to be compiled). Then webpack doesn’t seem to be able to find the missing ones (like `.dev).

    “compilerOptions”: {
    “paths” :{
    “@environment”: [“config/config.prod”]
    }
    },
    “include”: [
    “config/config.*”
    ],

Leave a Reply

Your email address will not be published. Required fields are marked *