Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Environment variables in Typescript with Webpack

I am having trouble declaring globals in Typescript, using Webpack's DefinePlugin. I was hoping to get some input on what I am doing wrong.

I created an environment variable in my .bash_profile:

export API_KEY_GOOGLE_MAPS=xxxxxxxxxxxxxxxx

In my webpack.config.js, I have the following lines:

...
plugins: [
  new webpack.DefinePlugin({
    API_KEY_GOOGLE_MAPS: JSON.stringify(process.env.API_KEY_GOOGLE_MAPS),
  }),
],
...

Inside index.tsx (I am using React), I do the following:

declare var API_KEY_GOOGLE_MAPS: string;

console.log(API_KEY_GOOGLE_MAPS)

This produces the following error, at the line containing console.log:

ReferenceError: API_KEY_GOOGLE_MAPS is not defined

Does anybody have any leads?

like image 285
bbalan Avatar asked Dec 14 '17 19:12

bbalan


People also ask

How do I pass an environment variable in webpack?

The webpack command line environment option --env allows you to pass in as many environment variables as you like. Environment variables will be made accessible in your webpack. config. js .

How do you call an environment variable 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.

Does webpack work with TypeScript?

Webpack allows TypeScript, Babel, and ESLint to work together, allowing us to develop a modern project. The ForkTsCheckerWebpackPlugin Webpack plugin allows code to be type-checked during the bundling process. Next up is a quiz to test our knowledge of this module.


1 Answers

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);
like image 138
sdgfsdh Avatar answered Sep 20 '22 11:09

sdgfsdh