51

Similar to an Angular 14 generated project I want to have separate development and production environments but when creating a project using ng new:

ng new my-app

this does not create the environments folder or set this up.

enter image description here

R. Richards
  • 24,603
  • 10
  • 64
  • 64
Mohamed Abouelnasr
  • 630
  • 1
  • 3
  • 8

5 Answers5

87

See Angular - Configure Environment Specific Defaults

EDIT:- As predicted, GitHub Issue

After the release of Angular CLI 15.1, a generation schematic will be available to add environment files for all existing build configurations within a project. Example usage:

ng g environments


To manually create:

If you want to recreate environments, follow these steps:

  • Create environments directory

  • Create your custom environments

    • environment.ts
    • environment.prod.ts
    • environment.staging.ts etc.
  • Update your angular.json or project.json to do fileReplacements where the paths are from project root to the environment file for replace and with:

  "configurations": {
       "production": {
          ...
          "fileReplacements": [
            {
              "replace": "apps/some-app/src/environments/environment.ts",
              "with": "apps/some-app/src/environments/environment.prod.ts"
            }
          ],
        },
        "development": {
          ...
        }
      },
      "defaultConfiguration": "production"
    },
Andrew Allen
  • 6,512
  • 5
  • 30
  • 73
  • I initially deleted as I'm not yet sure it this'll actually work i.e. if `fileReplacements` will still work. Undeleted and I'll let someone tell me since this answer referenced in a comment – Andrew Allen Nov 24 '22 at 10:02
  • 1
    I confirmed this to work. You just need to edit and remove the "apps/some-app" part (the pending edits queue is full). Then I put `export default "hello dev"` and `export default "hello prod"` in the environments and `import environment from "./environments/environment"; console.error(environment)` in main.ts. `ng build` shows the prod print outputted and `ng build -c development` shows the development print – Daniel T Nov 24 '22 at 10:33
  • Thanks,, for reference `apps/some-app` coming from nx workspace. But can be any path project root to environment files – Andrew Allen Nov 24 '22 at 10:35
  • 15
    I dont't understand why they removed the environment folder... It's a step backward to create the folder "manually". I used this very often for local development and production builds (server address as example) – Flo Nov 25 '22 at 16:58
  • 4
    ng g environments is not worked for me – Nimasha Madhushani Jan 03 '23 at 00:34
  • @NimashaMadhushani I suggest opening a new question if you're still facing issues. Include your angular version (>15.1) and `angular.json` file – Andrew Allen Jan 05 '23 at 10:06
  • I created directories manually. @AndrewAllen Still I am finding another issue. If you don't mind may I share the link to that question – Nimasha Madhushani Jan 05 '23 at 14:56
  • Also facing the same issue – Paul Brink Jan 31 '23 at 12:02
6

I haven't tested this all out yet but there seems to be a new command:

ng generate environments

Here is a Youtube video describing the steps needing to be done. There seems to be quite a bit of steps to configure afterward. But I plan on giving it a try.

https://www.youtube.com/watch?v=3IXwN4XJywQ

Laban
  • 2,304
  • 1
  • 14
  • 15
Sam
  • 4,766
  • 11
  • 50
  • 76
4

An Alternative

Because it looks like the normative environments setup is currently nonexistent and|or may becoming nonstandard, I thought I'd share an alternative pattern that I use for any non-Angular projects (including backend/Node) and now on Angular v15.0.0 that works very well.

It leverages the standard .env (and .env.{type}) files with just a little setup and looks something like this...

{app-name}
  |-environment
    |-env.ts
    |-path.ts
    |-index.ts
  |-.env
  |-.env.mock
  |-.env.dev
  |-.env.staging
  |-tsconfig.json
  |-package.json

package.json

{
  "scripts": {
    "SET TYPE=mock& start-command",  # "SET ..." for Windows setup.
    "SET TYPE=dev& start-command",
    "SET TYPE=qa& start-command"
  },
  "dependencies": {
    "dotenv": "n.n.n"
  }
}

tsconfig.json

{
    "compilerOptions": {
        "baseUrl": "./",
        "paths": {
            "@env": [ "environment/index.ts" ]
        },
    },
}

environment/index.ts

export { env } from './env';

environment/path.ts

module.exports = {
    '': '.env',
    'undefined': '.env',
    'prod': '.env',
    'mock': '.env.mock',
    'dev': '.env.dev',
    'qa': '.env.staging',
}[ process.env.TYPE ];  // npm script "SET TYPE={type}& start-command"

environment/env.ts

require('dotenv').config({ path: require('./path') });

export const env = new (class Environment {
    TYPE: string = '';
    NODE_ENV: string = '';
    PORT: number = -1;
    
    constructor(env: Environment = <Environment>{}) {
        const { TYPE, NODE_ENV, PORT } = { ...this, ...env };
        
        this.TYPE = TYPE;
        this.NODE_ENV = NODE_ENV;
        this.PORT = PORT*1;
        
        return this;
    }
    
})({ ...process.env });

src/example.ts

import { env } from '@env';

const { TYPE, NODE_ENV, PORT } = env;
let http = HTTP;

if (TYPE === 'mock') http = mockHTTP;

export { http };

Disclaimer

"Angular is built with Angular CLI, which is a node application, but you aren't able to access process.env directly from within the app during that build process, as it's not processed as a Node application." -- Use process.env in Angular 5 environment

It would be very nice to find an elegant workaround for this.

Cody
  • 9,785
  • 4
  • 61
  • 46
2

The environments folder is no longer necessary in Angular 15.

If your workflow still needs that folder, you can downgrade with npm install -g @angular/cli@14.2.10, then create a new project with ng new.

Daniel T
  • 827
  • 9
  • 14
  • 1
    Do you know what we should use instead? What I can see they aren't adressing it in their blogpost. – Tommi Nov 24 '22 at 09:38
  • 1
    See Andrew Allen's answer if you still need this feature. According to my research it's the way people are suggesting to replace it with. I personally don't use this "environments" feature and I think they removed it because only experts or non-Angile teams are using it. Anyway, even the "enableProdMode" control has been moved somewhere else by Angular – Daniel T Nov 24 '22 at 09:50
  • 4
    Wait..... I use the environment files to store my environment-specific app configuration. They made quite a bold decision to axe it just because we don't need one property on an entire class.???? – samneric Jan 27 '23 at 23:25
  • 1
    @samneric It is still available, just not create when create app: `ng generate environments` https://angular.io/cli/generate#environments – rofrol Aug 23 '23 at 09:33
2

To the best of my knowledge, in new Angular versions, the environments folder is not created by default when generating a new project using the ng new command. However, you can easily set up separate development and production environments yourself by following these steps:

  1. Create the Environments folder manually in the root directory of your Angular project by typing the following command:

    mkdir src/environments
    
  2. Inside the environments folder, create two TypeScript files: environment.prod.ts and environment.ts by typing the following command:

    touch src/environments/environment.prod.ts
    touch src/environments/environment.ts
    
  3. Open the environment.prod.ts file and define the production environment variables specific to your project. Consider the following as an example:

    export const environment = {
      production: true,
      apiUrl: 'https://portfolio.com/api',
      // Other production environment variables if you have
    };
    
  4. Open the environment.ts file and define the development environment variables as follows:

    export const environment = {
      production: false,
      apiUrl: 'http://localhost:4200/api',
      // Other production environment variables if you have
     };
    
  5. Now, you can use the environment variables in your Angular code. As an example, you can import the environment file in a component and access the variables like the following:

    import { environment } from '../environments/environment';
    // Usage example
    if (!environment.production) {
      console.log('Development Mode');
    };
    
  6. With the above-mentioned steps, you have set up separate development and production environments in your Angular project. Now you can modify the environment variables in the respective files based on your project's requirements.

  • Note: Remember to update the values of apiUrl or other variables to match your actual API endpoints or any other environment-specific configurations.
desertnaut
  • 57,590
  • 26
  • 140
  • 166