簡體   English   中英

帶有 Webpack 的 Typescript 中的環境變量

[英]Environment variables in Typescript with Webpack

我無法使用 Webpack 的 DefinePlugin 在 Typescript 中聲明全局變量。 我希望得到一些關於我做錯了什么的意見。

我在.bash_profile創建了一個環境變量:

export API_KEY_GOOGLE_MAPS=xxxxxxxxxxxxxxxx

在我的 webpack.config.js 中,我有以下幾行:

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

index.tsx (我使用的是 React),我執行以下操作:

declare var API_KEY_GOOGLE_MAPS: string;

console.log(API_KEY_GOOGLE_MAPS)

這會在包含console.log的行產生以下錯誤:

ReferenceError: API_KEY_GOOGLE_MAPS is not defined

有人有線索嗎?

我這樣做的方法是在我的項目文件的根目錄中有一個 .env 文件(將其添加到 .gitignore)。

在該文件中,我定義了我的項目環境變量(可以通過將每個變量添加到它自己的行中來分隔其他變量):

NODE_ENV=development

然后使用 dotenv npm 模塊,我可以訪問任何 webpack 文件(例如服務器端 expressJS 文件)中的值。

// 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)
    })
],

現在我可以在由 webpack 轉譯的應用程序中引用它:

console.log(NODE_ENV); // development

create-react-app環境變量應以REACT_APP_為前綴:

注意:您必須創建以 REACT_APP_ 開頭的自定義環境變量。 除了 NODE_ENV 之外的任何其他變量都將被忽略,以避免意外暴露機器上可能具有相同名稱的私鑰。 如果開發服務器正在運行,更改任何環境變量都將要求您重新啟動它。

來自“ 添加自定義環境變量”文檔。

您應該將這些環境變量添加到.env文件中,而不是將它們添加到.bash_profile文件中。 將根據構建(即startbuild )選取適當的文件,並且應用程序將更易於共享和部署。

回答我自己的問題:我的項目是使用create-react-app ,根據其文檔,環境變量是通過這種方式訪問​​的:

console.log(process.env.API_KEY_GOOGLE_MAPS)

webpack.DefinePlugin()不是必需的。

其他答案需要create-react-app所以我會提供我的。

首先,將插件添加到您的 Webpack 配置中:

const webpack = require("webpack");

module.exports = {
  // ... 
  plugins: [
    new webpack.DefinePlugin({
      MY_ENV_VAR: JSON.stringify(true),
    }),
  ],
};

接下來,在 TypeScript 中聲明變量:

declare var MY_ENV_VAR : string | undefined;

最后,您可以訪問代碼中的變量:

console.log(MY_ENV_VAR);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM