Madhuri Bhamre
Madhuri Bhamre

Reputation: 25

How to use environment variable in import syntax?

I am using angular v5. I want to do something like

import { OwnedSetABI } from 
`../constant/${environment.envName}/OwnedSetContractABI`;

I have OwnedSetContractABI file in different folder and want to use then according to environment. for example for dev env the path of OwnedSetABI would be '../constant/dev/OwnedSetContractABI', for production env the path of OwnedSetABI would be '../constant/production/OwnedSetContractABI'. But ES6 not allowd to use variable in import syntax. How I can achieve this scenario?

Upvotes: 2

Views: 1225

Answers (3)

Arun Selvaraju
Arun Selvaraju

Reputation: 1

I solved this problem by replacing import statement with require statement. Try replacing

import { OwnedSetABI } from 
`../constant/${environment.envName}/OwnedSetContractABI`;

with

const OwnedSetABI = require(`../constant/${environment.envName}/OwnedSetContractABI`);

Thanks.

Upvotes: 0

Fateh Mohamed
Fateh Mohamed

Reputation: 21367

i think you can define multiple configurations inside your angular.json

     "production": {
     "fileReplacements": [
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/environment.prod.ts"
            }
          ]
     },
     "dev": {
         "fileReplacements": [
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/environment.dev.ts"
            }
          ]

     }

and in each environment file you can import a specific OwnedSetABI from different directories environment.prod.ts

export * from './prod/OwnedSetContractABI';

so you have just import that way

import {environment} from '../environments/environment';

and run build and serve for the wanted configuration dev or prod

ng build --env=production

or

ng serve --env=production

Upvotes: 2

Francisco Santorelli
Francisco Santorelli

Reputation: 1338

Check your angular.json and ctrl + f for "fileReplacements" and there you should see the answer you look for.

In short, you tell angular what to replace environment.ts with, depending on environment.

Any env-dependant variables put them in those environment files with the same variable name, and they would automatically be replaced on serve or build.. and then just import those in environment.ts (the one that is bound to be replaced)

Upvotes: 0

Related Questions