如何根据 Nodejs 中的环境变量在 Angular 中插入动态脚本
How to Insert dynamic script in Angular based on environment variable in Nodejs
我在 Angular 应用程序的 index.html 文件底部有一个脚本,我想根据 Node.js 中的环境变量更改它。我想将一个 public api 密钥用于暂存,另一个用于生产。
我对暂存和生产使用相同的 grunt 构建,所以我不知道按照建议 here 动态更改构建常量是否是最佳解决方案。
关于如何处理这个问题有什么想法吗?
当环境变量为NODE_ENV=production时,插入:
<script>
Stripe.setPublishableKey('pk_live_NN4j94VX3mtz2wJtIO3bmH');
</script>
当环境变量为 NODE_ENV=staging 时,插入:
<script>
Stripe.setPublishableKey('pk_test_LgtEvbZwjC2GaKQYE3I6NnzuA');
</script>
我会使用 grunt-ng-constant
来管理您的 angular 环境变量,然后在您的 angular app.config()
函数而不是您的文档中初始化 Stripe。
我的偏好是使用 angular-stripe
在 angular 启动进程中管理 Stripe。如果您使用这两个键配置您的应用程序,这也可能会让您的生活更轻松。这是我的一个应用程序中的一些示例代码。
var $app = angular.module('app', ['angular-stripe']);
$app.constant('devDomains', ['localhost', 'staging.mydomain.com']);
$app.constant('stripePubKeyStaging', 'STRIPE_PUB_KEY_HERE');
$app.constant('stripePubKey', 'STRIPE_PUB_KEY_HERE');
$app.config(function(devDomains, stripePubKey, stripePubKeyStaging, stripeProvider) {
if (devDomains.indexOf(document.location.hostname) !== -1 || document.location.search.indexOf('stripe-test-key') !== -1) {
// if you're running your angular app on local or staging, use the test key. Additionally
// if you load your page with ?stripe-test-key you can force your production app
// to use the test key in order to debug something on live if you'd like.
stripeProvider.setPublishableKey(stripePubKeyStaging);
} else {
stripeProvider.setPublishableKey(stripePubKey);
}
});
我在 Angular 应用程序的 index.html 文件底部有一个脚本,我想根据 Node.js 中的环境变量更改它。我想将一个 public api 密钥用于暂存,另一个用于生产。
我对暂存和生产使用相同的 grunt 构建,所以我不知道按照建议 here 动态更改构建常量是否是最佳解决方案。
关于如何处理这个问题有什么想法吗?
当环境变量为NODE_ENV=production时,插入:
<script>
Stripe.setPublishableKey('pk_live_NN4j94VX3mtz2wJtIO3bmH');
</script>
当环境变量为 NODE_ENV=staging 时,插入:
<script>
Stripe.setPublishableKey('pk_test_LgtEvbZwjC2GaKQYE3I6NnzuA');
</script>
我会使用 grunt-ng-constant
来管理您的 angular 环境变量,然后在您的 angular app.config()
函数而不是您的文档中初始化 Stripe。
我的偏好是使用 angular-stripe
在 angular 启动进程中管理 Stripe。如果您使用这两个键配置您的应用程序,这也可能会让您的生活更轻松。这是我的一个应用程序中的一些示例代码。
var $app = angular.module('app', ['angular-stripe']);
$app.constant('devDomains', ['localhost', 'staging.mydomain.com']);
$app.constant('stripePubKeyStaging', 'STRIPE_PUB_KEY_HERE');
$app.constant('stripePubKey', 'STRIPE_PUB_KEY_HERE');
$app.config(function(devDomains, stripePubKey, stripePubKeyStaging, stripeProvider) {
if (devDomains.indexOf(document.location.hostname) !== -1 || document.location.search.indexOf('stripe-test-key') !== -1) {
// if you're running your angular app on local or staging, use the test key. Additionally
// if you load your page with ?stripe-test-key you can force your production app
// to use the test key in order to debug something on live if you'd like.
stripeProvider.setPublishableKey(stripePubKeyStaging);
} else {
stripeProvider.setPublishableKey(stripePubKey);
}
});