我采用了一种稍微不同的方法——在 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
而无需重新发明轮子
- 我们有一个强类型、有据可查的配置映射,可以从我们的 TS 代码中的任何地方导入和使用