6 年后,答案应该是:使用 Nconf。这很棒。
//
// yourrepo/src/options.js
//
const nconf = require('nconf');
// the order is important
// from top to bottom, a value is
// only stored if it isn't found
// in the preceding store.
// env values win all the time
// but only if the are prefixed with our appname ;)
nconf.env({
separator: '__',
match: /^YOURAPPNAME__/,
lowerCase: true,
parseValues: true,
transform(obj) {
obj.key.replace(/^YOURAPPNAME__/, '');
return obj;
},
});
// if it's not in env but it's here in argv, then it wins
// note this is just passed through to [yargs](https://github.com/yargs/yargs)
nconf.argv({
port: {
type: 'number'
},
})
// if you have a file somewhere up the tree called .yourappnamerc
// and it has the json key of port... then it wins over the default below.
nconf.file({
file: '.yourappnamerc'
search: true
})
// still not found, then we use the default.
nconf.defaults({
port: 3000
})
module.exports = nconf.get();
然后在任何其他文件中
const options = require('./options');
console.log(`PORT: ${options.port}`);
现在您可以像这样运行您的项目:
$ yarn start
# prints PORT: 3000
$ YOURAPPNAME__PORT=1337 yarn start
# prints PORT: 1337
$ yarn start --port=8000
# prints PORT: 8000
$ echo '{ "port": 10000 }' > .yourappnamerc
$ yarn start
# prints PORT: 10000
如果你忘记了你有什么选择
$ yarn start --help
# prints out all the options