score:5

Accepted answer

create-react-app environment variables should be prefixed with react_app_:

note: you must create custom environment variables beginning with react_app_. any other variables except node_env will be ignored to avoid accidentally exposing a private key on the machine that could have the same name. changing any environment variables will require you to restart the development server if it is running.

from the "adding custom environment variables" documentation.

you should be adding these environment variables to your .env file(s) in place of adding these to your .bash_profile file. the appropriate file will be picked up depending on the build (i.e. start or build), and the application will be easier to share and deploy.

score:0

answering my own question: my project was generated using create-react-app, and according to its documentation, environment variables are accessed this way:

console.log(process.env.api_key_google_maps)

webpack.defineplugin() is not required.

score:4

the other answers require create-react-app so i will offer mine.

first, add the plugin to your webpack configuration:

const webpack = require("webpack");

module.exports = {
  // ... 
  plugins: [
    new webpack.defineplugin({
      my_env_var: json.stringify(true),
    }),
  ],
};

next, declare the variable in typescript:

declare var my_env_var : string | undefined;

finally, you can access the variable in your code:

console.log(my_env_var);

score:5

the way i do it is to have a .env file(add it to .gitignore) in the root of my project files.

within that file i define my project environment variables(additional variables can be separated by adding each to it's own line):

node_env=development

then using the dotenv npm module i can access the values in any webpack file(or server side expressjs file for example).

// in the command line
$ npm install --save dotenv

// at the top of the webpack config file
require('dotenv').config();

// in the plugins of the webpack config
plugins: [
    new webpack.defineplugin({
        'node_env': json.stringify(process.env.node_env)
    })
],

now i can reference it within my app being transpiled by webpack:

console.log(node_env); // development

Related Query

More Query from same tag