Search code examples
typescriptwebpackdotenv

Typescript dotenv returning undefined when accessed by a variable


I have set a helper to access my process.env as below:

export const env = (key: string, def: any = null): string|any => {
    console.log(process.env["APP_ENV"], process.env[key], key === "APP_ENV")
    // @ts-ignore
    if ( process.env[key] instanceof String && process.env[key].length) {
        return process.env[key]
    }
    return def
}

This is injected to all my modules with plugins:

plugins: [
    new Dotenv(),
    new webpack.ProvidePlugin({
        env: ['./plugins/config_helper', 'env'],
    })
]

when I access it as env("APP_ENV") I get a baffling result from my debug prints.

develop undefined true

Can someone explain this behavior? More specifically, why does process.env produce undefined when I access it via a variable?


Solution

  • For the why part of the question look at this answer: https://stackoverflow.com/a/66626413/1882663

    Below is solution that I'm using in my app, note that I'm using prefix REACT_APP_ for all my env variables.

    webpack.config.js:

    require('dotenv').config()
    
    const getReactEnvs = () => {
        const envs = {}
        
        Object.keys(process.env).forEach(env => {
            if(env.startsWith('REACT_APP_')) envs[env] = process.env[env]
        })
    
        return envs
    }
    
    module.exports = [
        new ProvidePlugin({
            process: 'process/browser',
        }),
        new DefinePlugin({
            'process.env': JSON.stringify({ ...getReactEnvs() }),
        }),
    ]