@lifebyspot/ts-transform-inject-environment-variables
TypeScript icon, indicating that this package has built-in type declarations

1.0.3 • Public • Published

Transformer Plugin: Inject Environment Variables

This ttsc compliant transformer allows you to inject environment variables on your code at compile time.

This is done by replacing the initializers of variable declarations. You can learn how to do that, too!

Setup

Run npm install to save the package in your project.

npm install -D @lifebyspot/ts-transform-inject-environment-variables 

Usage

Basically, there's two main scenarios you can use to inject variables using this plugin.

First, the variables defined using process.env as initializer.

export const API_BASE_URL = process.env.API_BASE_URL;
export let ASDASDASDASD = process.env.ASDASDASDASD;

or

export const API_BASE_URL = process.env['API_BASE_URL'];

Will be converted into:

export const API_BASE_URL = 'https://api.example.com';
export let ASDASDASDASD;

Second, the variables defined using a destructuring syntax.

export const { API_BASE_URL } = process.env;

Will be converted into:

export const { API_BASE_URL = 'https://api.example.com' } = {};

Bonus: If no environment variable is found, the variable will be uninitialized. However, it's possible to use the nullish coalescing operator or object destructuring default values to define a default value to assign when this happens.

const { HOME = '/root' } = process.env;
const PATH = process.env.PATH ?? '/bin:/usr/bin';

Will be converted to:

const { HOME = '/root' } = {};
const PATH = '/bin:/usr/bin';

Note: Do not define variables that might be undefined as const.

export const ASDASDASDASD = process.env.ASDASDASDASD;

This is because, when running the compiled version, would end up with an uninitialized const variable, which is basically a violation of Javascript's rules.

export const ASDASDASDASD; // Not valid

Prerequisites

Configuration

Add the plugin to the plugins list on tsconfig.json.

{
    // ...
    "compilerOptions": {
        "plugins": [
            {
                "transform": "@lifebyspot/ts-transform-inject-environment-variables",
                "type": "config"
            }
        ]
    }
    // ...
}

Running

Just run ttsc against your project working directory. That it.

Contributing

Just send an issue or a PR! ;)

Dependencies (0)

    Dev Dependencies (3)

    Package Sidebar

    Install

    npm i @lifebyspot/ts-transform-inject-environment-variables

    Weekly Downloads

    0

    Version

    1.0.3

    License

    MIT

    Unpacked Size

    19.7 kB

    Total Files

    8

    Last publish

    Collaborators

    • gbellospot
    • austin-spot
    • phernandez-spot
    • jennyluo
    • brandon-spot
    • devops.getspot