安装node-config和@types/config后
yarn add config
yarn add --dev @types/config和添加配置,如lorenwest/节点-配置所述
// default.ts
export default {
server: {
port: 4000,
},
logLevel: 'error',
};当我试图在我的应用程序中使用时:
import config from 'config';
console.log(config.server);我发现了一个错误:
src/app.ts(19,53): error TS2339: Property 'server' does not exist on type 'IConfig'.发布于 2018-06-12 09:50:52
config.get实用程序可用于获取配置值,如下所示:
import config from 'config';
const port: number = config.get('server.port');发布于 2020-04-20 20:40:30
我正在采取一种稍微不同的方法--在JavaScript中定义变量,并在TypeScript中访问它们。
使用下列文件夹结构:
├── config
│ ├── custom-environment-variables.js
│ ├── default.js
│ ├── development.js
│ └── production.js
└── server
├── config.ts
└── main.ts我在根config/文件夹中定义配置。例如:
// config/default.js
module.exports = {
cache: false,
port: undefined // Setting to undefined ensures the environment config must define it
};
// config/development.js
module.exports = {
port: '3000'
}
// config/production.js
module.exports = {
cache: true
}
// config/custom-environment-variables.js
module.exports = {
port: 'PORT'
}现在,在TypeScript中,我定义了一个接口来提供更好的自动完成&文档,并编写一些桥接代码将配置从node-config拉到我的配置映射中:
// server/config.ts
import nodeConfig from 'config';
interface Config {
/** Whether assets should be cached or not. */
cache: boolean;
/** The port that the express server should bind to. */
port: string;
}
const config: Config = {
cache: nodeConfig.get<boolean>('cache'),
port: nodeConfig.get<string>('port')
};
export default config;最后,我现在可以在任何TypeScript代码中导入和使用我的配置变量。
// server/main.ts
import express from 'express';
import config from './config';
const { port } = config;
const app = express();
app.listen(port);这种方法有以下好处:
node-config提供的丰富的和经过战斗测试的特性,而不需要重新发明轮子。发布于 2019-03-18 11:44:20
使用此"import * as config from ' config ';“而不是”从‘config’导入配置;“
import * as config from 'config';
const port = config.get('server.port');
console.log('port', port);
// port 4000配置/开发.config
{
"server": {
"port": 4000
}
}并设置NODE_ENV=development
export NODE_ENV=development注意:如果使用默认设置,则不需要此NODE_ENV集。
https://stackoverflow.com/questions/50813591
复制相似问题