【发布时间】:2019-12-30 23:28:58
【问题描述】:
我在编译脚本中定义了几个环境变量。但是,我只能从 webpack.config.babel.js 文件中访问这些变量,并且我需要在反应代码(前端)中访问这些变量。
我在这里找到了一种方法:https://blog.container-solutions.com/deploying-configurable-frontend-web-application-containers,但我认为放入元标记数据(例如数据库密码)并不是一个好主意。尽管如此,尝试只为 .env 文件做的方式对我不起作用:(
那么,我的问题是如何从前端访问环境变量?
编辑我:
我已经应用了@robi932 的明智建议,但它对我不起作用:(
webpack.config.babel.js
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 代码中使用它,但是当我尝试访问它时,它不起作用:(
console.log("HomeLF1Content process.env.URL_FEB_API: " + URL_FEB_API);
或
console.log("HomeLF1Content process.env.URL_FEB_API: " + process.env.URL_FEB_API);
这是我在 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"
我做错了什么?
解决方案:
感谢https://medium.com/@trekinbami/using-environment-variables-in-react-6b0a99d83cf5@Shubham Jain 提供的这个链接,我终于找到了一个很好的解决方案来为前端定义环境变量。
然后,我将解释我为解决问题所采取的步骤。
首先,我们需要为每个环境提供两个 .env 文件。现在,我们有两个环境:开发和生产。因此,.env.development 将是我们要配置所有开发变量的文件,而 .env 将是我们要配置所有生产变量的文件。
第二,要选择之前创建的文件之一,我们需要告诉节点要编译哪个文件,所以在我们的编译脚本中,我们必须定义一个我们正在调用的变量NODE_ENV,我们将使用“开发”或“生产”进行初始化。
开发脚本:
"clean": "rm -rf ./dist",
"compile-dev": "NODE_ENV=development 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",
生产脚本:
"clean": "rm -rf ./dist",
"compile": "NODE_ENV=production webpack -p --config ./webpack.config.babel.js --progress",
"start": "npm run clean && npm run compile && cross-env NODE_ENV=production babel-node src/server/server.js --ignore ./node_modules",
第三,现在,我们将在 webpack.config.babel.js 文件中添加一些代码,以根据 NODE_ENV 变量的值选择环境变量。
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 文件中,在 plugin 部分,我们必须在编译项目时添加对这个变量的访问:
plugins: [
//With this entry we can get access to the environment variable for front-end
new webpack.DefinePlugin(envKeys),
],
最后,要在前端访问这些变量,我们可以使用process.env.VARIABLE_NAME 轻松访问它们,其中 VARIABLE_NAME 是文件 .env 或 . env.development.
请投票给@Shubham Jain 给出的答案,因为他的链接对我非常有用。
【问题讨论】:
-
你说的是服务器的 .env 还是客户端的 .env?
-
我正在讨论客户的 .env。使用服务器环境变量我没有问题。谢谢。
-
看看有没有帮助medium.com/@trekinbami/…
标签: javascript reactjs webpack environment-variables