我已经在客户端使用Create-React-App创建了一个应用程序,在服务器端使用了express。我为环境变量创建了一个.env
文件,其中将存储DB_USER
和DB_PASSWORD
。
在服务器端,我想使用猫鼬连接,并且.env
变量将是连接到mongodb服务器时的凭据。
当我执行process.env.DB_USER
时,在终端控制台中得到未定义的变量。相反,我得到了我的OS环境变量和NodeJS变量。但是,当我在Chrome控制台/客户端执行console.log(process.env.DB_USER)
时,确实看到了变量。
我尝试安装dotenv
,dotenv-webpack
并配置我的webpack.config
,但似乎没有任何效果。我还为变量添加了REACT_APP_*
作为前缀,但仍未定义值。
另外,当我使用dotenv
并将require('dotenv').config()
设置到我的index.js
文件中时,它也会抱怨fs
的依赖关系?
我只是无法在服务器文件夹中读取环境变量,理想情况下,最好在客户端和服务器文件夹中读取这些变量。有人遇到过这个问题吗?我只是在学习如何使用Create-React-App
和webpack
。您的帮助将不胜感激!
server.js
//server.js
const express = require('express');
const path = require('path');
const router = require('./routes/routes.js')
const app = express();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const user = process.env.REACT_APP_DBUSER;
const password = process.env.REACT_APP_DBPASSWORD;
//tells express frontend will reside in client folder
app.use(express.static(path.join(__dirname, '../build')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
console.log('node', process.env);
console.log(user);//this is undefined
//connect to mongoDB
mongoose.connect(`mongodb://${user}:${password}@ds141812.mlab.com:41812/note_app_db`, { useNewUrlParser: true });
let conn = mongoose.connection;
conn.on('error', console.error.bind(console, 'connection:'));
conn.once('open', () => {
console.log('connected to database');
});
//pass in routes from router const
app.use('/',router)
module.exports=app;
webpack.config
const webpack = require('webpack');
const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const Dotenv = require('dotenv-webpack');
const config = {
entry: __dirname + '/client/js/index.jsx',
output: {
path: __dirname + '/build',
filename: 'bundle.js'
},
resolve: {
extensions: ['.js', '.jsx', '.css']
},
module: {
rules: [
{
test: /\.jsx?/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['@babel/preset-env', '@babel/react']
}
},
{
test: /\.(png|jpg|svg|gif|mp4|mov)$/,
use: [{
loader: 'file-loader',
options: {
name: '/assets/[name]-[hash:8].[ext]'
}
}]
},
{
test: /\.scss$/,
loader: 'style-loader!css-loader!sass-loader'
}
]
},
devServer: {
publicPath: '/',
contentBase: __dirname + '/build',
port: 5000,
historyApiFallback: {
index: 'index.html'
}
},
plugins: [
new CopyWebpackPlugin([
{ from: './client/index.html', to: './index.html' }
]),
new Dotenv({
path: './.env',
}),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify("development"),
REACT_APP_DBUSER: JSON.stringify(process.env.REACT_APP_DBUSER),
REACT_APP_DBPASSWORD: JSON.stringify(process.env.REACT_APP_DBPASSWORD)
}
})
]
}
module.exports = config
index.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
require('dotenv').config({path: '../../.env'});//is this how it supposed to look like???
ReactDOM.render(<App />, document.getElementById('root'));
package.json
{
"name": "note_app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@babel/core": "^7.1.5",
"@babel/preset-env": "^7.1.5",
"@babel/preset-react": "^7.0.0",
"axios": "^0.18.0",
"babel-loader": "^8.0.4",
"body-parser": "^1.18.3",
"copy-webpack-plugin": "^4.6.0",
"css-loader": "^1.0.1",
"dotenv": "^6.1.0",
"dotenv-webpack": "^1.5.7",
"env-cmd": "^8.0.2",
"express": "^4.16.4",
"file-loader": "^2.0.0",
"mongoose": "^5.3.11",
"node-sass": "^4.10.0",
"nodemon": "^1.18.6",
"react": "^16.6.1",
"react-dom": "^16.6.1",
"react-modal": "^3.6.1",
"react-router-dom": "^4.3.1",
"react-scripts": "2.1.1",
"sass-loader": "^7.1.0",
"style-loader": "^0.23.1",
"webpack-cli": "^3.1.2"
},
"scripts": {
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"webpack": "webpack --mode development",
"dev": "npm run webpack && nodemon bin/www"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
]
}
.env文件
REACT_APP_DBUSER="username"
REACT_APP_DBPASSWORD="password"
答案 0 :(得分:1)
找到了解决方案,所以dotenv
很好,我已经卸载了dotenv-webpack
。为了使server.js
文件读取环境变量,我只需要在此文件中添加require('dotenv').config();
。走应该很好!
答案 1 :(得分:0)
替换我以前的错误答案。
除了使用该dotenv-webpack软件包之外,您还可以使用此软件包:
https://www.npmjs.com/package/dotenv
理论上,您可以从插件中删除该new DotEnv
,然后在调用require('dotenv').config()
时,您的webpack.config.js应该可以访问这些环境变量,然后您的webpack定义插件会选择将它们注入到您的代码中