angular - 如何在 nativescript 中访问 webpack 环境变量?
问题描述
我想在 webpack.config.js 中存储一个环境变量,当我在 Nativescript 中将应用程序与 webpack 捆绑时设置。目标是即使在捆绑之后也对环境变量保密。
我怎么做?
我相信这应该是可能的,如下所述(但未详细说明):https ://docs.nativescript.org/performance-optimizations/bundling-with-webpack ://docs.nativescript.org/performance-optimizations/bundling-with-webpack 。
但我无法让它在测试中工作。我是 webpack 的新手,所以我可能会遗漏一些明显的东西。
为了简单起见,我将调用变量“simple_env_variable”,并给它一个值“here_is_the_value!”。
要访问这个变量,我想我会用:
$ tns build ios --bundle --env.development --env.simple_env_variable=here_is_the_value!
我在 webpack.config.js 中输入什么代码,然后在我的 ts 组件中输入什么代码来访问它?
例如:
webpack.config.js:
module.exports = env => {
...
const config = {
...
plugins: [
...
new webpack.DefinePlugin({
"simple_env_variable": /**What Do I Enter Here***/
酷组件.ts:
export class CoolComponent {
public myVariable = /**What Do I enter here to access the variable in webpack.config.js? **/
解决方案
以 Nick Lliev 的回答为起点,从这里的讨论中,升级我的 webpack 和 nativescript 设置后,以下内容对我有用:
webpack.config.js:
new webpack.DefinePlugin({
"global.TNS_WEBPACK": "true",
"process": undefined,
"myGlobal.MySecret": JSON.stringify(env.first_property)
}),
主页.ts:
import {OnInit...
declare let myGlobal: any
@Component...
export class MainPageComponent implements OnInit {
...
ngOnInit(): void {
console.log(myGlobal.MySecret) // prints "yaySecret" with the run command I have below
}
然后工作 tns 运行命令:
$ tns run ios --bundle --env.uglify --env.aot --env.first_property="yaySecret"
推荐阅读
- wagtail - wagtil中的slugurl和pageurl有什么区别
- scala - 未找到配置键:类型安全的 ConfigFactory.load 在哪里查找 Scala 多项目中的配置文件?
- javascript - AWS Lambda - 如何处理函数中的请求处理顺序
- vb.net - 两次打开颜色对话框?
- spring-cloud-stream - Spring Cloud Stream融合模式注册表不起作用
- python - 如何在 Tkinter 的另一个框架内添加一个框架?
- konvajs - 绘制矩形不能遮蔽我的图像
- web-services - Spring 集成 web 服务 jms
- sql - 获取表中下一行的值总和
- java - Java 8:如何转换列表