Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Environment Variables 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?

example:

if (Environment['ENV'] == 'staging') console.log('testing');

which would compile to (the redundant, but efffective) if ('staging' == 'staging') ... on the above environment?

like image 559
Tyler Sebastian Avatar asked Nov 16 '16 00:11

Tyler Sebastian


People also ask

How do I create an environment variable in 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. If your TypeScript file runs in the browser, then there is no process.

How do you read environment variables in TypeScript?

To use environment variables in a TypeScript Node. js project, we need to add @types/node as a development dependency. You can access the variables using the process. env object.

Are environment variables strings?

The value of an environment variable is a string of characters. For a C-language program, an array of strings called the environment shall be made available when a process begins.


2 Answers

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.

like image 181
Vincent Avatar answered Sep 19 '22 12:09

Vincent


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

like image 23
basarat Avatar answered Sep 19 '22 12:09

basarat