Environment properties for Angular 2 applications served by Webpack?

I work with the standalone Angular console created by JHipster and served by the Spring boot server. I am looking to serve an application with various properties based on the environment (local, dev, prod, etc.).

I see a lot of messages about setting up the webpack assembly for the environment , but I need to specify the URLs and other data in my Angular 2 4.x app directly - data that changes whether I run the application in dev or during production. Is such a configuration possible for each environment when starting Angular through webpack?

0
source share
2 answers

dotenv-webpack.

webpack.config.js

const  Dotenv  =  require('dotenv-webpack');
...
plugins: [
   new  Dotenv({
      path:  './.env'
   })
]

.env

URL=http://example.com
ENV=PROD
...

process.env :

constructor(private http:HttpClient) {
     http.get(`${process.env.URL}`).subscribe(t=> {
        ...
     });
}

.

+1

DotEnv, DefinePlugin, -. - noob, , , process.env( ).

, :

  • webpack.envName.js , .
  • DefinePlugin , . "" webpack.common , .
  • DefinePlugin "process.env". , js .
  • , node, mvn .., dev, . dev , local .
    1. - .

. webpack.local.js plugins:

...
new webpack.DefinePlugin({
'process.env': {
    NAME: JSON.stringify('local'),
    API_URL: JSON.stringify('http://localhost:8000/'),
}
})
...

, fakeService typescript:

~/src/main/webapp/fake-service.ts
@Injectable
export class FakeService {
    private URL_ROOT = process.env.API_URL + 'api/v2/externalService/resource/';
    constructor(private http: HTTP) {}
    get(): Observable<any> {
        if(process.env.NAME == 'local') {
            console.log("Calling url at " + this.URL_ROOT);
        }
       return this.http.get(this.URL_ROOT).map((res: Response) => res.json());
    }
}

, ( ). , process.env , Configuration, , .

0

Source: https://habr.com/ru/post/1649107/


All Articles