[英]angular2-starter config file (with environment (testing, production) variables aka .env or .conf)
在許多框架中,例如PHP Laravel,都有帶有本地配置的文件(不同於開發,測試,生產環境)。 如何為angular-starter項目提供這樣的配置文件,其中將包含所有本地環境變量值(例如Google Analytics(分析)的鍵,snetry.io等)?
我提出以下解決方案也適用於AoT:
在主目錄中包含angular-starter項目的存儲庫中(其中是package.json,docker和其他頂級文件夾文件),我們創建帶有以下主體的文件.env.example.js
:
// copy this file to './.env.js' and modify variables in EnvData
var Env = {
// If some of below variable is NULL then that varabile feature is off
google_analaytics : 'XX-YYYYYYYY-Z',
sentry_clientKey_publicDSN: 'https://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx@sentry.io/yyyyyy',
// ... here you can put more variables
};
module.exports = Env;
然后,我們將此文件復制到.env.js
並將最后一個文件包含到.gitignore
文件中。 然后,我們將文件.env.example.js
和.gitignore
提交到git存儲庫中。
我們使用.js文件而不是.ts(打字稿),因為生成index.html
文件時,webpack可以在js文件上使用。 好的,讓我們展示如何在webpack配置文件中使用此變量。 讓我們轉到./config/webpack.common.js
並找到以下代碼並添加以下行:
new HtmlWebpackPlugin({
template: 'src/index.html',
title: METADATA.title,
chunksSortMode: 'dependency',
metadata: METADATA,
inject: 'head',
env: require('../.env') // <-- new line
}),
然后在Google Analytics(分析)部分的./src/index.html
中,您可以更改為:
<% if (htmlWebpackPlugin.options.env.google_analaytics) { %>
<!-- Google Analytics: -->
<script>
(function(A,n,g,u,l,a,r){A.GoogleAnalyticsObject=r;A[l]=A[l]||function(){
(A[l].q=A[l].q||[]).push(arguments)},A[l].l=1*new Date();a=n.createElement(g),
r=n.getElementsByTagName(g)[0];a.async=1;a.src=u;r.parentNode.insertBefore(a,r)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', '<%= htmlWebpackPlugin.options.env.google_analaytics %>', 'auto');
ga('send', 'pageview');
</script>
<% } %>
在打字稿模塊/組件/類(.ts文件)中,您可以通過以下方式使用變量值(我們將js導入ts)(以下示例用於設置哨兵):
import * as Raven from 'raven-js'; // http://sentry.io
import * as Env from '../../.env.js';
...
let sentryDSN = Env['sentry_clientKey_publicDSN']
if(sentryDSN)
{
Raven.config(sentryDSN).install();
...
}
...
就這樣 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.