Environment Variables TypeScript

前端 未结 2 1090
遇见更好的自我
遇见更好的自我 2021-01-17 08:03

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 = \'st

2条回答
  •  悲&欢浪女
    2021-01-17 08:45

    No, this is not possible.

    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.

    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.

    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.

提交回复
热议问题