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?
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.
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.
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.
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.
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.
Example showing how to use it for build output toggles : https://basarat.gitbooks.io/typescript/content/docs/tips/build-toggles.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With