在前端开发中,经常需要在不同的环境中使用不同的配置来支持程序的开发、测试和部署。使用 wires-config 可以非常方便地管理这些配置,同时可以避免硬编码带来的问题。
安装
在使用 wires-config 之前,需要先安装该 npm 包。可以在终端中执行以下命令:
npm install wires-config --save
接下来就可以在项目中通过 require()
引入 wires-config:
const wiresConfig = require('wires-config');
配置文件
wires-config 的核心是配置文件。配置文件一般为 JSON 格式,并按照不同的环境分别存放在不同的目录中。例如:
-- -------------------- ---- ------- -------- --- ------- - --- ------------ - --- ------------ - - --- --------------- - - --- ----------------- - - --- ---------------- - --- ----------- - --- ---------------- --- ------------- --- ---- --- ---
在上面的目录结构中,config/
目录为 wires-config 默认的配置目录,包含了默认和各个环境特有的配置文件:
default.json
是默认配置文件,其中定义了一些基础的配置项,其他环境特有的配置项将覆盖默认配置项。development/
目录存放开发环境的配置文件。使用NODE_ENV=development
启动应用程序时,应使用该目录下对应的配置文件。production/
目录存放生产环境的配置文件。使用NODE_ENV=production
启动应用程序时,应使用该目录下对应的配置文件。
在每个环境特有的配置文件中,可以覆盖默认配置文件中的任意配置项,并添加新的配置项。例如,假设 default.json
中定义了 port
配置项为 3000:
{ "port": 3000, "db": { "url": "mongodb://localhost/myapp", "user": "", "pass": "" } }
development/config.dev.json
中可以采用以下方式覆盖 port
配置项:
{ "port": 4000 }
在开发环境中,wires-config 会自动读取 default.json
和 development/
目录中的配置文件,将它们合并成一个 JSON 对象,并返回。该对象中,以 development/
目录中的配置文件中的配置为准。因此,上面的例子中,port
配置项的值为 4000。
使用方法
在项目中需要读取配置项时,可以使用 wires-config 中提供的 get()
函数。该函数接受一个参数,即配置项的名称,返回该配置项在当前环境下的值。例如,如果想要获取上面例子中 port
配置项的值:
const wiresConfig = require('wires-config'); const port = wiresConfig.get('port'); console.log('port:', port);
get()
函数也支持默认值。如果在指定环境的配置文件和默认配置文件中都找不到该配置项,将返回默认值。例如:
const wiresConfig = require('wires-config'); const host = wiresConfig.get('host', 'localhost'); console.log('host:', host);
上面的代码中,如果在配置文件中找不到 host
配置项,则使用默认值 'localhost'
。
示例代码
下面是一个使用 wires-config 的示例代码:
const wiresConfig = require('wires-config'); const server = app.listen(wiresConfig.get('port'), () => { const host = server.address().address; const port = server.address().port; console.log(`App listening at http://${host}:${port}`); });
在上面的代码中,app
是一个 Express 应用程序实例,get('port')
函数返回应用程序运行时监听的端口号。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/600671108dd3466f61ffe363