$ npm install @feathersjs/configuration --save
feathersress/configuration 是 node-config 的包装器, 允许配置服务器端Feathers应用程序.
默认情况下, 这个实现将在 config/* 中 查找 保留约定的 default.json. 根据 配置文档, 您可以组织 “应用程序部署的分层配置”. 有关如何实现此操作的更多信息, 请参阅下面的使用部分.
@feathersjs/configuration 模块是一个app配置函数,它接受一个根目录(通常类似于应用程序中的 _dirname)和配置文件夹(默认设置为 config):
const feathers = require('@feathersjs/feathers');
const configuration = require('@feathersjs/configuration');
// Use the application root and `config/` as the configuration folder
let app = feathers().configure(configuration())
默认情况下,Feathers将使用项目源目录根目录中的 config/ 目录.要改变这一点,例如,如果你在 server/ 目录下安装了Feathers并且想要你的配置在 server/config/,你必须在导入 @feathersjs/configuration 之前 在 app.js 中设置 NODE_CONFIG_DIR 环境变量:
例如, 在 server/app.js:
process.env['NODE_CONFIG_DIR'] = path.join(__dirname, 'config/')
const configuration = require('@feathersjs/configuration')
上面的代码是可移植的,所以你可以将你的 config/ 目录与其余的Feathers文件保存在一起.例如,即使您将目录从 server/ 更改为 amazing-server 等,它也可以工作.
(@feathersjs/configuration不直接使用 NODE_CONFIG_DIR 环境变量,而是使用它所使用的 node-config 模块.有关配置 node 的更多信息-config设置,请参阅 配置文档Wiki页面.
@feathersjs/configuration 使用以下变量机制:
给定根和配置路径在该路径中加载 default.json
还尝试在该路径中加载 <NODE_ENV>.json,如果找到,则扩展默认配置
浏览每个配置值并在应用程序上设置它(通过 app.set(name,value)).
如果值是有效的环境变量(例如 NODE_ENV),请改用它的值
如果值以 ./ 或 ../ 开头,则将其转换为相对于配置文件路径的绝对路径
如果值被转义(以 \ 开头), 则始终使用该值(例如 \\NODE_ENV 将变为 NODE_ENV)
default 和 <env> 配置都可以是模块,它们用 module.exports = {...} 和 .js 文件后缀提供计算设置.有关示例,请参阅 test/config/testing.js. 上面列出的所有规则都适用于 .js 模块.
在 config/default.json 中我们想要使用本地开发环境和默认的MongoDB连接字符串:
{
"frontend": "../public",
"host": "localhost",
"port": 3030,
"mongodb": "mongodb://localhost:27017/myapp",
"templates": "../templates"
}
在 config/production.json 中,我们将使用环境变量(例如由Heroku设置)并使用 public/dist 来加载前端生成版本:
{
"frontend": "./public/dist",
"host": "myapp.com",
"port": "PORT",
"mongodb": "MONGOHQ_URL"
}
现在它可以在我们的 app.js 中使用:
const feathers = require('@feathersjs/feathers');
const configuration = require('@feathersjs/configuration');
let conf = configuration();
let app = feathers()
.configure(conf);
console.log(app.get('frontend'));
console.log(app.get('host'));
console.log(app.get('port'));
console.log(app.get('mongodb'));
console.log(app.get('templates'));
console.log(conf());
如果你现在运行
node app
// -> path/to/app/public
// -> localhost
// -> 3030
// -> mongodb://localhost:27017/myapp
// -> path/to/templates
或者通过在 config/custom-environment-variables.json 中设置自定义环境变量:
{
"port": "PORT",
"mongodb": "MONGOHQ_URL"
}
$ PORT=8080 MONGOHQ_URL=mongodb://localhost:27017/production NODE_ENV=production node app
// -> path/to/app/public/dist
// -> myapp.com
// -> 8080
// -> mongodb://localhost:27017/production
// -> path/to/templates
您还可以使用参数覆盖这些变量.阅读更多关于如何使用 node-config