gpt4 book ai didi

reactjs - 如何在React中加载环境变量

转载 作者:行者123 更新时间:2023-12-03 13:22:30 24 4
gpt4 key购买 nike

我一直在尝试在 React 中加载环境变量,但我似乎无法弄清楚。我尝试了多种方法:

使用 dotenv-webpack 包加载它们

webpack.config.dev.js

const merge = require('webpack-merge');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const template = require('html-webpack-template');
const Dotenv = require('dotenv-webpack');
const baseConfig = require('./webpack.config.base');

module.exports = merge(baseConfig, {
mode: 'production',
plugins: [
new HtmlWebpackPlugin({
template,
inject: false,
appMountId: 'app',
mobile: true,
lang: 'es-ES',
title: 'My App',
meta: [
{
name: 'description',
content: 'My App',
},
],
}),
new Dotenv(),
],
});

.env

API_HOST=http://localhost:8000
REACT_APP_API_HOST=http://localhost:8000

直接将其传递到 package.json 脚本上:

"start": "webpack-dev-server --config ./webpack.config.dev.js"

在 webpack 命令上使用 .env

webpack --env.API_HOST=http://localhost:8000

使用webpack.environmentPlugin

const webpack = require('webpack');
const merge = require('webpack-merge');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const template = require('html-webpack-template');
const baseConfig = require('./webpack.config.base');

module.exports = merge(baseConfig, {
mode: 'development',
devtool: 'cheap-module-source-map',
devServer: {
publicPath: '/',
contentBase: './dist',
compress: true,
stats: 'minimal',
overlay: true,
historyApiFallback: true,
port: 8081,
hot: true,
},
plugins: [
new HtmlWebpackPlugin({
template,
devServer: 'http://localhost:8081',
inject: false,
appMountId: 'app',
mobile: true,
lang: 'es-ES',
title: 'My App',
meta: [
{
name: 'description',
content: 'React template.',
},
],
}),
new webpack.EnvironmentPlugin({
API_HOST: 'http://localhost:8000',
}),
],
});

这些方法都不起作用,当我尝试访问 React 代码中的 process.env 变量时,我得到 undefined我知道我可能做错了什么吗?

最佳答案

当我想为 Firebase 项目提供设置但不将它们加载到公共(public)存储库中时,我自己已经与环境变量作斗争有一段时间了。

据我所知,您需要命名的环境变量应始终以前缀 REACT_APP_ 开头。您可以在任何您喜欢的位置定义它们,但是如果您使用 create-react-app 工具创建应用程序,那么您可以将变量放入 .env 文件或其他一些文件中 - ( https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables )

当我想制作自己的文件时,我的痛苦就开始了,因为我有两个不同的 Firebase 项目 - 一个用于暂存,一个用于生产。

我最终使用了 react-app-env 模块,它有助于:- 定义我自己的文件 - staging.env 和 production.env- 自动为我的变量添加 REACT_APP_ 前缀

例如:

我已在 staging.env 文件中定义了 Firebase ApiKey:API_KEY=xxxxxxxxxxxxxxxxxx

当我在 firebase.js 文件中使用它时,我将其用作:

const config = {
apiKey: process.env.REACT_APP_API_KEY,
}

为了确保我针对暂存环境(Firebase 项目)进行开发,我已将 package.json 更改为:

"scripts": {
"start": "react-app-env --env-file=staging.env start",
},

希望有帮助!

关于reactjs - 如何在React中加载环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57174217/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com