Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Request: Method to pass environment variables during build vs file. #4318

Open
DennisSmolek opened this issue Feb 1, 2017 · 129 comments
Open
Assignees
Labels
area: devkit/build-angular feature: under consideration Feature request for which voting has completed and the request is now under consideration feature Issue that requests a new feature
Milestone

Comments

@DennisSmolek
Copy link

OS?

Any, mostly a build/CI question

Versions.

1.0.0-beta.26

Reasoning

I really like the environment variables setup with the CLI and we have switched to using them. One problem though is we no longer have access to server set ENV variables which is how we pass information to certain things during deployment. Consider:

Bugsnag.releaseStage = environment.releaseStage;
// can't access process.env anymore with the CLI
  const commit = process.env.CI_COMMIT_ID;
  if (commit) Bugsnag.metaData = {
        commits: {
          id: commit
        }
      };

Codeship ENV variables

Being able to add the release stage, branch, and commit ID allows us to segment and track bugs/issues very accurately.
My problem is I know the build takes whatever stage I pass and replaces the environment.ts file so I can't just edit the file with a bash script (well, if I know EXACTLY the build before hand I could) but it would be nice to be able to pass env variables in the build line.

Consider: ng build --prod could be: ng build --prod --envVar:commitId: CI_COMMIT_ID

which would append the variable after the file gets merged

export const environment =  {
    production: true, 
    commitId: 'ca82a6dff817ec66f44342007202690a93763949'
}

something like this would ensure it gets added to the right file and at the right time/place..

Then we could do:

  const commit = environment.commidId;
  if (commit) Bugsnag.metaData = {
        commits: {
          id: commit
        }
      };
@Brocco Brocco added command: build feature Issue that requests a new feature labels Feb 1, 2017
@Brocco
Copy link
Contributor

Brocco commented Feb 1, 2017

@hansl we were just discussing this, thought you might have something to add

@yuzhva
Copy link

yuzhva commented Feb 8, 2017

Why not make ENV variables available in process.env again?

I'm really feeling comfortable with Heroku Config Vars and Codeship environment variables, I already set up them, moved all my sensitive data like secret keys to angular-cli environment.dev.ts, BUT I can't use them.(

export const environment = {
  production: false,
  GOOGLE_RECAPTCHA_SITE_KEY: '6Le...Zq'
};

Because there is no way to access variables from test env or production like:

export const environment = {
  production: false,
  GOOGLE_RECAPTCHA_SITE_KEY: process.env.GOOGLE_RECAPTCHA_SITE_KEY
};

in my environment.test.ts and environment.prod.ts

Need to thinking on using third party packages like dotenv or env2

P.S: Is it hard to implement configuration like this:

...
"scripts": [],
"environments": {
        "source": "environments/environment.ts",
        "dev": "environments/environment.dev.ts",
        "test": "environments/environment.test.ts",
        "prod": "environments/environment.prod.ts"
      },
"processEnv": [
         "CUSTOM_ENV_VAR",
         "GOOGLE_RECAPTCHA_SITE_KEY",
         ...
]

So then there will be opportunity access them from process.env.CUSTOM_ENV_VAR, etc.

@k10der
Copy link

k10der commented Apr 13, 2017

I ran into the same issue a day ago. And for a temporary workaround, that works (just checked it with Codeship), I just added the "prebuild" script, that generates the appropriate environment file using current env variables. ejs is used as a template processor due to it's simplicity.

scripts/prebuild.js - this is a script with the required logic

#!/usr/bin/env node

const fs = require('fs');
const path = require('path');

const ejs = require('ejs');

const environmentFilesDirectory = path.join(__dirname, '../src/environments');
const targetEnvironmentTemplateFileName = 'environment.prod.ts.template';
const targetEnvironmentFileName = 'environment.prod.ts';

// Define default values in case there are no defined ones,
// but you should define only non-crucial values here,
// because build should fail if you don't provide the correct values
// for your production environment
const defaultEnvValues = {
  PREFIX_STORAGE_TYPE: 'localStorage',
  PREFIX_USER_TOKEN_FIELD_NAME: 'userToken',
};

// Load template file
const environmentTemplate = fs.readFileSync(
  path.join(environmentFilesDirectory, targetEnvironmentTemplateFileName),
  {encoding: 'utf-8'}
);

// Generate output data
const output = ejs.render(environmentTemplate, Object.assign({}, defaultEnvValues, process.env));
// Write environment file
fs.writeFileSync(path.join(environmentFilesDirectory, targetEnvironmentFileName), output);

process.exit(0);

src/environments/environment.prod.ts.template - this is a template file, that generates the required environment file. Notice, that PREFIX_BACKEND_URL isn't provided in scripts/prebuild.js script in defaultEnvValues, because in production it should be defined only by build environment variables.

export const environment = {
  production: true,
  backendUrl: '<%= PREFIX_BACKEND_URL %>',
  storageType: '<%= PREFIX_STORAGE_TYPE %>',
  userTokenFieldName: '<%= PREFIX_USER_TOKEN_FIELD_NAME %>'
};

package.json - there are some changes here. In scripts/prebuild.js shebang (#!) style is used, so "prebuild" is just a pointer to the script file. And to make it work it must be marked as executable, that's why "postinstall" script is added either.

{
  ...
  "scripts": {
    ...
    "build": "ng build --prod --aot",
    "prebuild": "./scripts/prebuild.js",
    ...
    "postinstall": "chmod +x ./scripts/*.js"
  },
  ...
  "devDependencies": {
    ...
    "ejs": "^2.5.6",
    ...
  }
}

@DennisSmolek
Copy link
Author

@k10der this is great, this is similar to what we did. What we do is actually move the environment scripting out of angular totally. We have a single environment.ts file for all builds and use a custom script to generate the correct values via the env variables.

I still think this should be something within the CLI but there are of course workarounds.

@k10der
Copy link

k10der commented Apr 14, 2017

@DennisSmolek, I also think, that handling of process.env variables should be built-in in cli. And your approach to use a single environment file, that is generated by external tool makes sense: my dev environment variables are currently stored in the project repository, which is OK unless I'll start using some 3rd party APIs with private keys. So I guess one-environment-file approach should be used in future angular-cli versions.

@AmirSasson
Copy link

Injecting environment variables during build seems essential. Any ETA for supporting this in the ng cli?

@davidwalter0
Copy link

Why would common cross platform method for OS configuration support of env variables be excluded?

Unless there's a strong argument against 12factor that is being proposed for angular?

@zpydee
Copy link

zpydee commented May 13, 2017

I'd also really like to be able to use process.env variables. I'm deploying to docker swarms and the capability to be able to include variables in a compose file is important to my application.

@avatsaev
Copy link

very needed for dockerizing the apps indeed

@carlosthe19916
Copy link

@k10der Do you have any repository on github that is using the solution you proposed? I'd like to check it because I could not find any real solution on the internet.

@k10der
Copy link

k10der commented May 20, 2017

Hey, @carlosthe19916. I have a sample project, that I use just for practicing in Angular2+. It's not a production ready and you probably won't get any benefit from running it, but I use the proposed solution there. And it's exactly as I described it in this topic.

@emreavsar
Copy link

+1

@GaryB432
Copy link

Hi friends... What I think I want is to access environment variables at run time (in addition to build time as under discussion here.) For continuous integration purposes, I want to build only once, then deploy that same dist folder to my staging, qa, and prod environments using environment variables set with my CI provider on my runtime box. At first noodling process.env seems to equal {}. Do you feel I'm doing something wrong either technically or with the build-once-deploy-many approach?

@michaelarnauts
Copy link

@GaryB432

This is also my use case. I'm thinking to ignore the Angular CLI environments and use a plain old JavaScript include that sets my environment vars in a window.environment var.

Then, I can just deploy a different JavaScript include file and have different variable values with the same build output.

@michaelarnauts
Copy link

Workaround ahead. Might work fine in your setup, might not.

I've used two angular cli environments (dev and prod). Values that need to exists at build time are defined in environment.ts or environment.prod.ts. Values that need to be available during runtime are fetched from the window._env array in the environment.*.values.js file.

Production and Staging are using the same environment.prod.ts file, since this is used at build time, and you only want to do one build.

src/environment/environment.ts

export const environment = {
    production: false,
    backendUrl: (<any>window)._env.backendUrl,
};

src/environment/environment.prod.ts

export const environment = {
    production: true,
    backendUrl: (<any>window)._env.backendUrl,
};

src/environment/environment.values.js (development variables)

window._env = {
    backendUrl: 'https://localhost:7000',
};

src/environment/environment.prod.values.js (production variables)

window._env = {
    backendUrl: 'https://api.example.com/',
};

src/environment/environment.stag.values.js (staging variables)

window._env = {
    backendUrl: 'https://api-staging.example.com/',
};

Next, you need to make sure that you add this line to your index.html. We will place this file there during deployment.

...
<head>
  ...
  <script src="/assets/env.js"></script>
</head>
...

The tests also need to have these values, so I've loaded them at the top of the test.ts bootstrap file.

src/test.ts

// Load default environment values
import 'environments/environment.values.js';
...

Finally, you need to change your deployment/development scripts so that you execute this command:

For production:

cp src/environments/environment.prod.values.js dist/assets/env.js

For staging:

cp src/environments/environment.stag.values.js dist/assets/env.js

For development:

cp src/environments/environment.values.js dist/assets/env.js

I'm using Gitlab CI for deployment, and I execute this command before copying the dist/ to the production/staging server.
For local development, I'm using a Makefile to set everything up, so I execute the copy the file there right before I'm running the ng serve.

You might also want to add the dist/assets/env.js to your .gitignore.

@FranklinYu
Copy link

How about the webpack.DefinePlugin mentioned in this answer? How do we integrate it into Angular CLI?

@jaguardev
Copy link

jaguardev commented Jul 23, 2017

Another quick solution (any shell command in a template could break everything)

package.json:

"prebuild": "eval \"echo \\\"$(cat src/environments/environment.ts.template)\\\"\" > src/environments/environment.ts",

environment.ts.template:

export const environment = {
  production: false,
  clientId: \"${CLIENT_ID}\",
  apiId: \"${API_ID}\",
  authDiscoveryEndpoint: \"${AUTH_DISCOVERY_ENDPOINT}\"
};

Also, something like this could work better

perl -p -i -e 's/\$\{([^}]+)\}/defined $ENV{$1} ? $ENV{$1} : $&/eg' < src/environments/environment.ts.template | tee src/environments/environment.ts

@nh-nico
Copy link

nh-nico commented Jul 27, 2017

My current workaround is a pre and post build event which replaces a version-tag in my environment.prod.ts file
export const environment = { production: true, system: 'prod', version: '%VERSION%' };

install npm-replace:
npm install replace --save-dev

package.json
"build:prod": "ng build --env=prod --output-hashing=all --output-path=dist/prod --aot", "prebuild:prod": "replace '%VERSION%' $VERSION src/environments/environment.prod.ts", "postbuild:prod": "replace $VERSION '%VERSION%' src/environments/environment.prod.ts",

Jenkins runs it with: ($Tag is my release-tag, for example "1.0.0")
VERSION="$Tag" npm run build:prod

@GaryB432
Copy link

We wound up sing this Visual Studio Team Services extension in our release. Very happy with it.

@wvh-shanee
Copy link

wvh-shanee commented Aug 3, 2017

Adding my voice to this request--in the middle of doing DevOps work on three different Angular 4 applications and the lack of access to environment variables has made this much harder than it needs to be. I'm hopeful this can be rectified soon.

I agree with @GaryB432 that access at both build and runtime would be great, but I could settle with build time if need be.

@JWesorick
Copy link

To add to this, on Heroku I currently need to commit new code to change the env variables. Having access to process.env would let us change the environment variables through the browser and command line without needing to commit anything.

@GaryB432
Copy link

If anyone is interested we made a little command line util to add to your CD step. It takes an EJS template and processes with process.env variables context. We use it to grab our build provider's environment vars and stick them into a small global object script which is then loaded into index.html

@GaryB432
Copy link

GaryB432 commented Sep 1, 2017

Just adding to my comment above, if you guys are using Azure we created a build/release step that plugs environment variables into a small shim script. Very simple and meets our requirement, viz: build one dist folder and deploy it to multiple environments. I'm sure the underlying package on which it is based, the one I mentioned in the previous comment, is adaptable to other CI/CD ecosystems.

@kopz9999
Copy link

This CLI approach generates a file that doesn't messes up with the version control and keeps them on environment.ts

@ricardosaracino
Copy link

ricardosaracino commented Nov 17, 2020

Its pretty easy to inject a config into your application at runtime

https://www.tektutorialshub.com/angular/angular-runtime-configuration/

app.module.ts

..... 
 providers: [
    AppConfigService,
    {
      provide: APP_INITIALIZER,
      useFactory: (appConfig: AppConfigService) => {
        return () => appConfig.load();
      },
      deps: [AppConfigService],
      multi: true,
    },
    {
      provide: LOCALE_ID,
      useFactory: (localeService: LocaleService) => localeService.current,
      deps: [LocaleService],
    },
  ],
  bootstrap: [AppComponent],
})
export class AppModule {
}

app-config.service.ts

export class AppConfigService {

  constructor(private http: HttpClient) {
  }

  static _settings: IAppConfig;

  public get settings() {
    return AppConfigService._settings;
  }

  public load(): Promise<void> {

    const jsonFile = `config/config.${environment.name}.json`;

    return new Promise<void>((resolve, reject) => {
      this.http.get(jsonFile).toPromise().then((response: IAppConfig) => {
        AppConfigService._settings = response as IAppConfig;
        resolve();
      }).catch((response: any) => {
        reject(`Could not load file '${jsonFile}': ${JSON.stringify(response)}`);
      });
    });
  }
}

I just replace config.deploy.json with the appropriate file for the env my build is deployed to

image

@andrewatwood
Copy link

andrewatwood commented Nov 26, 2020

Just want to give another solution in the meantime that feels much less hacky to me, using the JSON tool jq, which is available on most package repositories and super lightweight to install.

For a while now, I've used this snippet to grab a value from package.json during build time and inject it into my app at runtime using the environment files.

import { version } from '../../package.json'; // your relative pathing may be different of course

export const environment = {
  production: false,
  version
}

There is a compiler option required to enable this sort of import (resolveJsonModule) but it works great.

Recently, I wanted more dynamic versioning based on information from my CI build pipeline, stuff like the build number and commit hash, and ended up on this GitHub issue. In AngularJS and gulp days, I'd used methods similar to those suggested here, stuff like string replacements prior to actual compilation, but those don't feel quite as a good in the ng build world.

I realized if I can just replace a value in package.json just prior to ng build, my environment.ts can just import it like it already has been with version and go about its business none the wiser.

So using only cat and jq, here's the one-liner to do it:

cat <<< $(jq '.version=env.VERSION' package.json) > package.json
ng build

This overwrites package.json with an identical copy, but with the version key set to the value of VERSION.

You can obviously customize this to be whatever key you'd like, like build or release, or even some nested value if you wanted, just check the jq docs for how to do that.

If you don't like touching your package.json file, you can also use some other variables.json file or whatever you'd like, and have default values that get overwritten so that Intellisense works properly. It's flexible enough to work with any JSON file of course.

Hope this helps someone else! Feels sufficiently un-hacky to me so I'm satisfied.

@RA80533
Copy link

RA80533 commented May 5, 2021

@andrewatwood, take a look at the npm-version command. You would use it like so to bump your version:

$ npm version --no-git-tag-version "${VERSION}"

@chihab
Copy link

chihab commented Aug 22, 2021

If it helps, I have created a builder to easily inject environment variables into your Angular applications at build time.

For the use case of the question, it would be used as follows:

NG_APP_COMMIT_ID=${CI_COMMIT_ID} ng build --prod

You can then access NG_APP_COMMIT_ID anywhere in your TypeScript and HTML code.

In your environment/component/service

const commitId = process.env.NG_APP_COMMIT_ID;

Directly in your template

<span> {{ 'process.env.NG_APP_COMMIT_ID' | env }} </span>
<span> {{ 'NG_APP_COMMIT_ID' | env }} </span>

In your index.html

<head>
  <title> Commit -  %NG_APP_COMMIT_ID% </title>
  <body><ng-app></ng-app></body>
</head>

You can also define Environment variables in a .env file and have extensions per NODE_ENV. It uses dotenv, and dotenv-expand behind the scenes.

I would also like to see this feature supported natively in @angular/cli as it is in the create-react-app and vue CLIs. In the meantime, I hope @ngx-env/builder can help.

@Maxl94
Copy link

Maxl94 commented Sep 23, 2021

@andrewatwood

Thanks a lot, this was really helpful.

I should admit, that I hat do adapt the settings in my tsconifg.json. I did need to set the following options under the compilerOptions, to import a JSON in environment.ts.

    "resolveJsonModule": true,
    "allowSyntheticDefaultImports": true,

In case some is asking, my import looks the following:

import env from '../../env.json';

// You can use the now env.SOME_SETTINGS to directly get the value

@angular-robot angular-robot bot added the feature: under consideration Feature request for which voting has completed and the request is now under consideration label Feb 1, 2022
@ngbot ngbot bot modified the milestones: Backlog, needsTriage Feb 1, 2022
@Gnyblast
Copy link

Gnyblast commented Aug 11, 2022

Workaround ahead. Might work fine in your setup, might not.

I've used two angular cli environments (dev and prod). Values that need to exists at build time are defined in environment.ts or environment.prod.ts. Values that need to be available during runtime are fetched from the window._env array in the environment.*.values.js file.

Production and Staging are using the same environment.prod.ts file, since this is used at build time, and you only want to do one build.

src/environment/environment.ts

export const environment = {
    production: false,
    backendUrl: (<any>window)._env.backendUrl,
};

src/environment/environment.prod.ts

export const environment = {
    production: true,
    backendUrl: (<any>window)._env.backendUrl,
};

src/environment/environment.values.js (development variables)

window._env = {
    backendUrl: 'https://localhost:7000',
};

src/environment/environment.prod.values.js (production variables)

window._env = {
    backendUrl: 'https://api.example.com/',
};

src/environment/environment.stag.values.js (staging variables)

window._env = {
    backendUrl: 'https://api-staging.example.com/',
};

Next, you need to make sure that you add this line to your index.html. We will place this file there during deployment.

...
<head>
  ...
  <script src="/assets/env.js"></script>
</head>
...

The tests also need to have these values, so I've loaded them at the top of the test.ts bootstrap file.

src/test.ts

// Load default environment values
import 'environments/environment.values.js';
...

Finally, you need to change your deployment/development scripts so that you execute this command:

For production:

cp src/environments/environment.prod.values.js dist/assets/env.js

For staging:

cp src/environments/environment.stag.values.js dist/assets/env.js

For development:

cp src/environments/environment.values.js dist/assets/env.js

I'm using Gitlab CI for deployment, and I execute this command before copying the dist/ to the production/staging server. For local development, I'm using a Makefile to set everything up, so I execute the copy the file there right before I'm running the ng serve.

You might also want to add the dist/assets/env.js to your .gitignore.

Life saver for an angular application that gets compiled and feed into a golang self-serving singleton binary application that has a configuration file like app.ini or something. So app.ini gets converted with a templating into js environment.js file that sets variables into window object and without need of re-compilation with changed environment files it still works.

So that each client can have their own app.ini and can benefit pre-compiled executable deployments as new version.

Thanks.

@soc221b
Copy link

soc221b commented Oct 9, 2022

Hi all, I wrote some packages related to this issue:

https://runtime-env.github.io/import-meta-env/

And here is an Angular example integrate with @angular-builders/custom-webpack.

Hope this package helps someone looking for this.

Feel free to give your feedback.

@francisrod01
Copy link

I wonder if the Angular docs could provide a straightforward implementation for it.

@arambazamba
Copy link

All the config injection approaches like using env vars (problem with testing) or config services are not very handy to use. Relying on a 3rd party contributors lib might help at the moment, but will they be maintained with all the upcoming Angular versions? I'd wish the Angular Team would come up with a build in solution that is DevOps + Artifacts friendly

@arambazamba
Copy link

@Gnyblast Thank you for sharing ... I used the window['env'] pattern that was used in the original article which caused the unit test to fail on build

@Gnyblast
Copy link

@Gnyblast Thank you for sharing ... I used the window['env'] pattern that was used in the original article which caused the unit test to fail on build

@arambazamba Do you really need to use real env data on testing? Since it's a test and you kind of mock everthing, you can also mock the environment file and pass that one in by configuring it for testing. So that way you don't have to worry about window['env'] pattern because you will be using a standart env file.

Let say:
src/environment/environment.prod.ts

export const environment = {
    production: true,
    backendUrl: (<any>window)._env.backendUrl,
    someOtherVariable: (<any>window)._env.someOtherVariable,
};

you can also have
src/environment/environment.test.ts

export const environment = {
    production: false,
    backendUrl: localhost:9001,
    someOtherVariable: "foo"
};

so that when you configure your envirnment to use environment.test.ts on testing it won't need to resolve the window env variables.

@kyubisation
Copy link
Contributor

To differentiate, because a few different issues seem to be conflated here.

Build-Time Configuration Currently available:

  • Replace files for different builds (with fileReplacements)

Desired (As stated in the feature request of this issue, if I understand it correctly):

  • Dynamically change configuration based on environment variables or cli parameters

Is @\clydin going to (only) focus on this? Will #3855 be taken into account?

Workarounds:

  • Dynamically create environment.prod.ts (or similar) before calling ng build --prod
  • Create a custom builder which dynamically creates/replaces the configuration in the host, or taps into the webpack configuration

Startup/Runtime Configuration Not supported by Angular CLI.

Is this out of scope for @\clydin? Should a separate issue be created for this?

Possible solutions:

From what I understand, nothing has changed since I wrote this two years ago, apart from other suggestions for Startup/Runtime Configuration, which is a different issue #3855 (and the Angular CLI team has indicated that they do not want to provide/maintain a solution to that in the CLI).

@arambazamba
Copy link

arambazamba commented Oct 18, 2022

@Gnyblast Thank for you input 👍 I had a similar thought after I replied to you … Actually I need the injection only on a prod build from which I will create the tagged artifact. So I removed the injection from the default environment file and left it only in environment.prod.ts. Works perfect for my needs

@LemonyPie
Copy link

Hey any updates on this?
Can Angular team allow usage of DotenvPlugin or something similar?

@ricardosaracino
Copy link

ricardosaracino commented Dec 16, 2022

@LemonyPie you can just load a assets file using

  public loadGenericReportsConfiguration(): Observable<ReportConfigurationGroup[]> {
    return this.http.get<ReportConfigurationGroup[]>('assets/reportEndpointMapping.json');
  }

image

@LemonyPie
Copy link

@LemonyPie you can just load a assets file using

  public loadGenericReportsConfiguration(): Observable<ReportConfigurationGroup[]> {
    return this.http.get<ReportConfigurationGroup[]>('assets/reportEndpointMapping.json');
  }

image

@ricardosaracino thanks for the idea, but in my team we used a single docker image for stage and prod. So I wanted to have a way to set the env variables during the image build to deploy the same image and be sure it's working correctly changing files seems not robust as thing may go wrong on prod after testing on stage

@kyubisation
Copy link
Contributor

See above: #4318 (comment)

From what I understand, nothing has changed since I wrote this two years ago, apart from other suggestions for Startup/Runtime Configuration, which is a different issue #3855 (and the Angular CLI team has indicated that they do not want to provide/maintain a solution to that in the CLI).

@LemonyPie I'm not sure I understand your requirement. If you just need to set environment variables for runtime configuration, you could use angular-server-side-configuration, which is designed to support configuring Angular applications in containers (e.g. in a Kubernetes environment), as I implemented it for that specific case.

@RicardoJBarrios
Copy link

Another way to do this is, as mentioned before, requesting the data from a file (maybe created by the HELM that deploy the node) or a property server. For this I created kuoki, with the Environment and the Environment Angular libraries.

There are many options, but I use to run away from variable injection in code because of race condition problems in the properties load or the dependency from objects like Window, that's an open door to attacks.

@motdotla
Copy link

motdotla commented Aug 3, 2023

As a new user of Angular I was really surprised environment variables weren't supported. Every other major front-end framework I've so far used has supported them.

After trying three or four of the recommended approaches here (spent half a day on them all), I personally settled on @chihab's ngx-env builder. It's a safe approach and works with minimal fuss (encouraging separation of secrets from code).

#4318 (comment)

Here's the result: https://www.dotenv.org/docs/frameworks/angular/vercel

@griest024
Copy link

vite supports .env files and import.meta env vars out of the box. Why use it in @angular-devkit/build-angular:application and disable this functionality?

@muuvmuuv
Copy link

Another idea is opening esbuild-plugins to allow us create plugins like "define" ourselfs. Here an example using @angular-builders/custom-esbuild. It is much more flexible instead of just only dotenv support.

import { getVersion } from './utils.mjs'

/** @type {import('esbuild').Plugin} */
export default {
	name: 'plugin-define',
	setup: async (build) => {
		const initialOptions = build.initialOptions
		initialOptions.define ??= {}
		initialOptions.define.APP_VERSION = JSON.stringify("x.x.x")
	},
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area: devkit/build-angular feature: under consideration Feature request for which voting has completed and the request is now under consideration feature Issue that requests a new feature
Projects
None yet
Development

No branches or pull requests