Dustin Cleveland
Dustin Cleveland

Reputation: 618

Angular 2/Webpack Environment Configurations

I would like to configure my Webpack build such that I can declare import { environment } from './environments/environment' in my Angular 2 components and have the import load environment.ts during development, but environment.prod.ts in production. How would I tell Webpack to replace the import during a build?

I'm looking for something very similar to the way projects created with Angular CLI are handling environment configurations. Unfortunately, I'd rather not use the CLI yet as it is still in beta, and I also haven't wrapped my head around how the project works and how to extend its build pipe.

I also want to avoid scattering conditional statements throughout my source code, so no using process.env.NODE_ENV in an if-statement everywhere that I want to import the environment file.

Upvotes: 6

Views: 6999

Answers (1)

Dustin Cleveland
Dustin Cleveland

Reputation: 618

Okay, I finally figured out a way to do this. First, the environment files:

environment.interface.ts:

export interface Environment {
    apiRoot: string,
    target: string
}

environment.dev.ts:

import { Environment } from './environment.interface';

export const environment: Environment = {
    target: 'dev',
    apiRoot: 'http://www.dev.api.com'
}

environment.prod.ts:

import { Environment } from './environment.interface';

export const environment: Environment = {
    target: 'prod',
    apiRoot: 'http://www.api.com'
}

environment.ts:

export { environment } from './environment.dev';

Then, import into the Angular components as normal:

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

Finally, using the NormalModuleReplacementPlugin in the webpack configuration:

webpack.prod.js:

module.exports = webpackMerge(commonConfig, {
  ...
  plugins: [
    ...
    new webpack.NormalModuleReplacementPlugin(/\.\/environment\.dev/, './environment.prod')
  ]
});

The first parameter in the NormalModuleReplacementPlugin is a Regex that matches environment.dev in environment.ts. The second parameter is the configuration module that you want to use in the build.

I'm sure that this could be made a bit more elegant by using some environment variables, but it's a good starting point.

Upvotes: 18

Related Questions