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?
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 .
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.
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.
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);
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