Javascript 如何从前端访问环境变量
我在编译脚本中定义了几个环境变量。但是,我只能从webpack.config.babel.js文件访问这些变量,我需要在react代码(前端)中访问这些变量 我在这里找到了这样做的方法:,但我认为,例如,在数据库密码等元标记数据中加入元标记不是一个好主意。尽管尝试只为.env文件执行此操作,但对我来说不起作用:( 所以,我的问题是,如何从前端访问环境变量 编辑I: 我已经应用了@robi932的明智建议,但它对我不起作用:( webpack.config.babel.jsJavascript 如何从前端访问环境变量,javascript,reactjs,webpack,environment-variables,Javascript,Reactjs,Webpack,Environment Variables,我在编译脚本中定义了几个环境变量。但是,我只能从webpack.config.babel.js文件访问这些变量,我需要在react代码(前端)中访问这些变量 我在这里找到了这样做的方法:,但我认为,例如,在数据库密码等元标记数据中加入元标记不是一个好主意。尽管尝试只为.env文件执行此操作,但对我来说不起作用:( 所以,我的问题是,如何从前端访问环境变量 编辑I: 我已经应用了@robi932的明智建议,但它对我不起作用:( webpack.config.babel.js plugins: [
plugins: [
new HtmlWebpackPlugin({
template: "./src/client/index.html", //where is our template
filename: "../index.html", //where we are going to put our index.html inside the output directory
minify: {
collapseWhitespace: true,
removeComments: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
useShortDoctype: true
}
}),
new MiniCssExtractPlugin({
filename: "css/bundle.css",
minify: {
collapseWhitespace: true,
removeComments: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
useShortDoctype: true
}
}),
new webpack.DefinePlugin({
URL_FEB_API: JSON.stringify(process.env.URL_FEB_API)
})
我定义了const URL_FEB_API,以便稍后在react js代码中使用它,但当我尝试访问它时,它不起作用:(
或
这是我在package.json中编译的脚本:
"clean": "rm -rf ./dist",
"compile-dev": "NODE_ENV=development URL_FEB_API=http://localhost:4000/api/feb/graphiql webpack -d --config ./webpack.config.babel.js --progress",
"dev": "npm run clean && npm run compile-dev && cross-env NODE_ENV=development nodemon --exec babel-node src/server/server.js --ignore ./src/client"
我做错了什么
解决方案:
感谢@Shubham Jain提供的这个链接,我终于找到了一个很好的解决方案,为前端定义环境变量
然后,我将解释一下我解决问题所遵循的步骤
首先,每个环境需要两个.env文件。现在,我们有两个环境:开发和生产。因此,.env.development将是配置所有开发变量的文件,.env将是配置所有生产变量的文件
其次,要选择之前创建的那些文件中的一个,我们需要告诉node要编译的文件,因此在我们的编译脚本中,我们必须定义一个变量,我们调用node_ENV,在这里我们将用“development”或“production”进行初始化
开发脚本:
制作脚本:
第三个,现在,我们将在webpack.config.babel.js文件中添加一些代码,根据NODE_ENV variable的值选择环境变量
import webpack from "webpack";
import path from "path";
import dotenv from "dotenv";
import fs from "fs";
/**
* Code to get the values of environment variables during compilation time for the front-end
*/
//Get the root path. Our .env files and webpack.config.babel.js files are in the root path
const currentPath = path.join(__dirname);
const basePath = currentPath + "/.env";
// We're concatenating the environment name to our filename to specify the correct env file!
const envPath = basePath + "." + process.env.NODE_ENV;
// Check if the file exists, otherwise fall back to the production .env
const finalPath = fs.existsSync(envPath) ? envPath : basePath;
// Set the path parameter in the dotenv config
const fileEnv = dotenv.config({ path: finalPath }).parsed;
// reduce it to a nice object, the same as before
const envKeys = Object.keys(fileEnv).reduce((prev, next) => {
prev[`process.env.${next}`] = JSON.stringify(fileEnv[next]);
return prev;
}, {});
第四个,在webpack.config.babel.js文件中,在插件部分,我们必须在编译项目时添加对该变量的访问:
plugins: [
//With this entry we can get access to the environment variable for front-end
new webpack.DefinePlugin(envKeys),
],
最后,要在前端访问这些变量,我们可以使用process.env.VARIABLE\u NAME
轻松访问它们,其中VARIABLE\u NAME是文件.env或.env.development中定义的变量之一
请投票给@Shubham Jain给出的答案,因为他的链接对我非常有用。Webpack提供了帮助您将变量从配置发送到react应用程序(定义插件)。
请参见此处如果您需要直接的解决方案,则可以使用第三方库,名为
dotenv webpack
。更多信息
有一个非常简单的方法: 第一步:转到应用程序的根文件夹,创建名为.env的文本文件 第二步:在新文件中创建自定义变量。Create React App(CRA)在每个自定义变量上强制使用前缀React_App。请注意,在绑定过程中忽略没有前缀的变量
REACT_APP_CLIENT_ID=jfjffffaddfeettgydgdffv
REACT_APP_KEY=aaddddawrfffvvvvssaa
第三步:将它们分配给变量,打印到屏幕上,等等,但它们是Javascript文件中的只读文件
console.log(process.env.REACT_APP_CLIENT_ID);
console.log(process.env.REACT_APP_KEY);
第四步:有一个名为NODE_ENV的内置环境变量。您可以从process.ENV.NODE_ENV访问它。此变量根据您当前所处的模式而变化。当您运行npm start时,它等于“development”,当您运行npm test时,它等于“test”,当您运行npm run build时,它等于“test”“生产”。此变量是特殊的,因为它可用于根据您的模式访问不同的环境配置。例如,如果您的生产和开发有不同的数据库(通常是为了防止干扰)您可以使用它有条件地访问某些变量。您不能手动覆盖NODE_ENV这一事实可以防止开发人员意外地将开发构建部署到生产环境中
第五步:打开.gitignore文件。我喜欢将.env和其他环境变量放在#misc下
为什么在遵循这些流程后仍无法正常工作?
- 确保在每个变量上都使用了前缀REACT\u APP
- 确认.env文件上的变量名与js文件上的变量名匹配。例如,REACT\u APP\u KEY in.env与process.env.REACT\u APP\u KY
- 如果开发服务器正在运行,请停止它,然后使用npm start it重新运行。我真的很难解决这个问题(变量是未定义的错误)。每次更新.env文件时,都需要停止服务器并重新运行它,因为环境变量仅在构建期间更新(变量是未定义的错误)
- 从变量的值中删除引号
注意:将敏感内容放入环境变量并不能保证它们的安全。它们在构建过程中被注入捆绑文件中,因此任何人都可以通过检查您的文件来查看它们。我发现它们的最大用途是在将代码推送到远程存储库之前隐藏信息。如何配置React项目中的.evn文件
REACT\u APP
,然后才能提及您的标识符
例如:REACT\u APP\u FIREBASE\u REALTIME\u DB
你说的是服务器的.env还是客户端的.env?我说的是客户端的.env。使用服务器环境变量我没有问题。谢谢。看看它是否有帮助。嗨@robi932!!!我已经应用了你的解决方案,但我做了一些错误的事情,因为它对我不起作用:(你休息了吗
import webpack from "webpack";
import path from "path";
import dotenv from "dotenv";
import fs from "fs";
/**
* Code to get the values of environment variables during compilation time for the front-end
*/
//Get the root path. Our .env files and webpack.config.babel.js files are in the root path
const currentPath = path.join(__dirname);
const basePath = currentPath + "/.env";
// We're concatenating the environment name to our filename to specify the correct env file!
const envPath = basePath + "." + process.env.NODE_ENV;
// Check if the file exists, otherwise fall back to the production .env
const finalPath = fs.existsSync(envPath) ? envPath : basePath;
// Set the path parameter in the dotenv config
const fileEnv = dotenv.config({ path: finalPath }).parsed;
// reduce it to a nice object, the same as before
const envKeys = Object.keys(fileEnv).reduce((prev, next) => {
prev[`process.env.${next}`] = JSON.stringify(fileEnv[next]);
return prev;
}, {});
plugins: [
//With this entry we can get access to the environment variable for front-end
new webpack.DefinePlugin(envKeys),
],
const Dotenv = require('dotenv-webpack');
module.exports = {
...
plugins: [
new Dotenv()
]
...
};
REACT_APP_CLIENT_ID=jfjffffaddfeettgydgdffv
REACT_APP_KEY=aaddddawrfffvvvvssaa
console.log(process.env.REACT_APP_CLIENT_ID);
console.log(process.env.REACT_APP_KEY);
REACT_APP_KEY=”AHEHEHR”
REACT_APP_KEY=AHEHEHR
REACT_APP_FIREBASE_REALTIME_DB=https://sample.firebaseio.com/
REACT_APP_FIREBASE_API=FFYTYt67567yhhhmnbdfgjd7erehfjdhfjd
process.env.REACT_APP_FIREBASE_REALTIME_DB
process.env.REACT_APP_FIREBASE_API
- Create .env file in root folder
- Open to .env file
--> REACT_APP_API_KEY= API KEY
**NOTE** starting with the prefix REACT_APP_ (IMPORTANT)
- Access it use process.env
eg const {REACT_APP_API_KEY,REACT_APP_TEMPLATE_ID,REACT_APP_SERVICE_ID} = process.env
- And use with template string
eg emailjs.send(`${REACT_APP_SERVICE_ID}`,`${REACT_APP_TEMPLATE_ID}`, values, `${REACT_APP_API_KEY}` )
.then((response) => {
console.log('SUCCESS!', response.status, response.text);
}, (err) => {
console.log('FAILED...', err);
});
When you do any changes or need to create at .env file don't forget to restart
appliction "npm start"