Environment Variables TypeScript

前端 未结 2 1091
遇见更好的自我
遇见更好的自我 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.

    0 讨论(0)
  • 2021-01-17 08:56

    is there a way for TypeScript to access that variable during compilation

    Yup. Prefer using process.env that works as is in node and can be used with webpack using --define.

    More

    Example showing how to use it for build output toggles : https://basarat.gitbooks.io/typescript/content/docs/tips/build-toggles.html

    0 讨论(0)
提交回复
热议问题