Search code examples
typescriptenvironment-variablestsconfig

How to set different paths under compilerOptions, depending on env variable


In my angular application I need to conditionally load modules depending on which environment the app is running (dev/prod). In the development environment it should be pointing to the libs folder of my local project, and for the production one it should point to an external package in the node_modules folder.

I have already tried to use the ternary operator as follows:

import { ModuleA as ModuleAExternal } from '@external/moduleA';
import { ModuleA } from '@moduleA';

@NgModule({
  declarations: [],
  imports: [
    ...
    environment.production ?   ModuleAExternal : ModuleA
  ]
})

Which works, but when the project is build I dont want to be forced to import both local and external packages.

So i would expect that the same

import { ModuleA } from '@moduleA';

would point to either the local lib or the external npm package depending on the environment. Since the @moduleA path is set in the tsconfig.json file under the compilerOptions as paths, is there a way to make this separation there?


Solution

  • You should have different environment file for development and production environments, from there you can define the moduleA. So let say they're environment.ts and environment.prod.ts (for prod)

    in environment.ts you an add

    import { ModuleA } from '@moduleA';
    
    export const environment = {
      ...
      ModuleA: ModuleA,
      ...
    

    and in environment.prod.ts

    import { ModuleA } from '@external/moduleA';
    
    export const environment = {
      ...
      ModuleA: ModuleA,
      ...
    

    So you can write them as

    @NgModule({
      declarations: [],
      imports: [
        ...
        environment.ModuleA
      ]
    })
    

    Hope this help