环境变量TypeScript [英] Environment Variables TypeScript
问题描述
假设我有一段代码,我只想在暂存环境中出现(或运行)。我在该环境中设置了一个环境变量(例如,ENV ='staging'),TypeScript有没有办法在编译期间访问该变量?
let's say I have a block of code that I'd like to only be present (or run) in a staging environment. I've set an environment variable in that enivronment (say, ENV = 'staging'), is there a way for TypeScript to access that variable during compilation?
示例:
if(Enivronment ['ENV'] =='staging')console.log('testing');
这将编译为(冗余但有效) if('staging'=='staging')...
关于上述环境?
which would compile to (the redundant, but efffective) if ('staging' == 'staging') ...
on the above environment?
推荐答案
不,这是不可能的。
如果你的TypeScript文件在Node中运行,您可以使用 process.env
因为它是一个常规的Node API - 但是在这种情况下,环境变量在运行时由您编译的文件访问,而不是在TypeScript的编译时访问。
If your TypeScript file runs in Node, you can use process.env
since it's a regular Node API - but in that case, the environment variable is accessed at runtime, by your compiled file, not at compile time by TypeScript.
如果您的TypeScript文件在浏览器中运行,则没有 process.env
,因此您甚至无法在运行时访问它。你可以使用像Webpack这样的工具来替换对的引用process.env
编译文件中的变量及其在构建时的相应值 - 但仍然不是TypeScript正在做的。
If your TypeScript file runs in the browser, then there is no process.env
, so you cannot even access it at runtime. You could use a tool like Webpack to replace references to process.env
variables in the compiled file with their respective values at build time - but that still is not TypeScript's doing.
所以不幸的是答案是否:TypeScript不能这样做,你必须使用其他东西(比如Webpack,甚至只是搜索和替换)将环境变量注入你的脚本。
So unfortunately the answer is no: TypeScript cannot do this, and you'll have to use something else (like Webpack, or even just a search and replace) to inject environment variables into your script.
这篇关于环境变量TypeScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!