loading...

Help, I’ve imported environment from environment.prod!

gparlakov profile image Georgi Parlakov Originally published at Medium on ・2 min read

i.e. the Angular environment file that gets replaced at build time.

How to automate the ‘never-again-import-environment-from-environment.prod’ vs staying vigilant and angry when people import it by mistake? Because VS Code and modern Typescript make it really simple to do this mistake. Just Ctrl + . and Enter on top of the squiggly underlinedenvironment and we get the environment. Usually, we get

import{environment} from ‘../environments/environment’;

But sometimes we get

import{environment} from ‘../environments/environment.prod’;

And what’s the difference you might ask? Well in the second case the module/component that we want to use the environment to make a logical decision, we always take the prod choice — no matter if in prod, staging or dev/QA. Even worse, when it’s from ‘../environments/environment.qa’ then the issue only manifests itself in production! Not cool!

All right so the answer is — be careful when importing — yes? Well, that might work in 99% of the cases. And it will bring sorrow and anger in that 1% when someone forgets and omits it.

So - how do we automate that?

The answer is tslint . And if you are not yet using it — this might be the time to start. It does static analysis on your code and can help with automating various checks. Including black-listing imports.

Here we have a CoreModule that imports the wrong environment. And a tslint.json that specifies the rule that all imports from prod, staging, etc. are blacklisted — not allowed. Be careful that you use a current version of tslint as older versions do not support regex.

Then we can do ng lint and we’ll get an error:

ERROR: c:/Users/myUser/test/src/app/core/core.module.ts:1:30 - This import is blacklisted by /\/.\*environment\.(prod|staging|demo|local)/

If we do this as part of our CI, then no more code with this import will be allowed in production. And the best part is — it’s automated and we won’t rely on everyone being careful when importing.

For older tslint versions, where upgrading is not an option one could potentially list many of the permutations of the import, based on how deep the import is :

"../environment/environment.prod",
"../../environment/environment.prod",
"../../../environment/environment.prod",
"../../../../environment/environment.prod",
and so on 

Posted on by:

gparlakov profile

Georgi Parlakov

@gparlakov

Angular and DotNet dev. RxJs explorer. Testing proponent. A dad. https://gparlakov.github.io/

Discussion

markdown guide