Webpack服务的Angular 2 App的基于环境的属性? [英] Environment-based properties for Angular 2 App Served by Webpack?

查看:78
本文介绍了Webpack服务的Angular 2 App的基于环境的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用由JHipster生成并由Spring Boot服务器提供服务的独立Angular控制台.我希望根据环境(本地,开发,生产等)为应用提供不同的属性.

I'm working with a standalone Angular console generated by JHipster and served by a Spring Boot server. I am looking to serve up the app with different properties based on the environment (local, dev, prod, etc).

我看到很多关于按环境配置webpack构建的帖子,但我需要直接在Angular 2 4.x应用程序中指定URL和其他数据-无论我在开发环境中还是在生产环境中运行该应用程序,这些数据都会发生变化.通过webpack启动Angular时,这种基于环境的配置是否可行?

I see a lot of posts about configuring the webpack build per-environment, but I need to specify URLs and other data into my Angular 2 4.x app directly- data that changes whether I am running the app in dev or in production. Is this type of per-environment configuration possible when we start Angular via webpack?

推荐答案

我推荐 dotenv- webpack 插件.

webpack.config.js

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

.env

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

这允许您使用process.env访问环境变量:

This allows you to use process.env to access the environment variables:

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

环境变量在构建时被替换.

The environment variables are subsituted at build time.

这篇关于Webpack服务的Angular 2 App的基于环境的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆