问题
I want to work with environment variables. Unfortunately, I am an inexperienced developer and decided very late to implement such a solution in my project.
I'm trying to inject environment variables, located in .env file, to all JS files (not all of them using environment variables, but I thought it would be faster and easier). Currently, I'm using dotenv package but it is obviously working in one file at once.
Should I use dotenv the standard way? Maybe there's a vulnerability I don't know of and that's why it is very unpopular to use environment variables this way.
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config();
}
回答1:
Like the comment on your file mentioned, you should have an entry point for your ENVs. You don't want to require('dotenv')
in every file.
Instead, create a new file (named something like environment.js
) that is in the utils or core folder.
require('dotenv').config();
/* eslint no-process-env:0 */
module.exports.default = {
env: process.env.env,
url: process.env.url,
apiUrl: process.env.apiUrl,
logLevel: process.env.logLevel,
db: {
host: process.env.db_host
port: process.env.db_port
}
// Grab everything in you .env file here
}
Then in each of your other files you can include your configs in a nice json object.
const config = require('../utils/environment');
dbConnector(config.db.host, config.db.port);
// blah blah blah
回答2:
You don't need to write require('dotenv').config() in every file. Just include this as the top statement in the index.js or the main file that got executed at the very first place when you run your program.
来源:https://stackoverflow.com/questions/58684642/should-i-call-dotenv-in-every-node-js-file