39ro
39ro

Reputation: 902

Angular environment variables on an ejected project

What I want to achieve?
Generating Environments variable depending on which NODE_ENV I am currently compiling on an Ejected project (ng eject). The same of targeting the environment using the Angular Cli: ng build --prod || ng build --dev.

What I tried?

  1. Setting my NODE_ENV in my scripts:

package.json

   ...
   "start": "NODE_ENV=development webpack-dev-server --port=4200",
   "start:prod": "NODE_ENV=production webpack-dev-server --port=4200",
   ...
  1. As suggested here, I changed my AotPlugin in webpack and replace it with:

    const environmentFiles = {
    'development': 'environments/environment.dev.ts',
    'production': 'environments/environment.prod.ts',
    };
    
    
    ...
    new AotPlugin({
    ...
     "hostReplacementPaths":
       "environments/environment.ts": environmentFiles[process.env.NODE_ENV]
    


  1. Try to run: npm run-script build:prod But the AotPlugin doesn't look to replace (hostReplacementPaths) for me the Environment variables file (environment.dev.ts || environment.prod.ts).


Any idea?

Similiar questions:

Environment file replacement is broken after switching to webpack...

Upvotes: 2

Views: 787

Answers (1)

39ro
39ro

Reputation: 902

Actually I just reverted my ejected project and back to use the CLI! But... I solved it just copying and pasting my environments into environment.ts with a prebuild script!

"prebuild:dev": "cp environment/environment.dev.ts environment/environment.ts"

you can also set your NODE variables to apply your conditions into your code:
How to set Environment variables from within package.json [Node.js]

For example:

npm run prebuild:dev
// will build my dev environment
npm run prebuild:prod
// will build my prod environment

Upvotes: 1

Related Questions