Dee*_*pak 8 node.js typescript node-config
安装后node-config
和@types/config
:
yarn add config
yarn add --dev @types/config
Run Code Online (Sandbox Code Playgroud)
并按照lorenwest / node-config中的描述添加配置:
// default.ts
export default {
server: {
port: 4000,
},
logLevel: 'error',
};
Run Code Online (Sandbox Code Playgroud)
当我尝试在我的应用中使用时:
import config from 'config';
console.log(config.server);
Run Code Online (Sandbox Code Playgroud)
我收到错误消息:
src/app.ts(19,53): error TS2339: Property 'server' does not exist on type 'IConfig'.
Run Code Online (Sandbox Code Playgroud)
SNA*_*lim 12
使用这个“import * as config from 'config';” 而不是“从‘配置’导入配置;”
import * as config from 'config';
const port = config.get('server.port');
console.log('port', port);
// port 4000
Run Code Online (Sandbox Code Playgroud)
配置/开发.json
{
"server": {
"port": 4000
}
}
Run Code Online (Sandbox Code Playgroud)
并设置 NODE_ENV=development
export NODE_ENV=development
Run Code Online (Sandbox Code Playgroud)
注意:如果使用默认值,则无需设置此 NODE_ENV
我采用了一种稍微不同的方法——在 JavaScript 中定义变量,并在 TypeScript 中访问它们。
使用以下文件夹结构:
??? config
? ??? custom-environment-variables.js
? ??? default.js
? ??? development.js
? ??? production.js
??? server
??? config.ts
??? main.ts
Run Code Online (Sandbox Code Playgroud)
我在根config/
文件夹中定义了配置。例如:
??? config
? ??? custom-environment-variables.js
? ??? default.js
? ??? development.js
? ??? production.js
??? server
??? config.ts
??? main.ts
Run Code Online (Sandbox Code Playgroud)
现在,在 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;
Run Code Online (Sandbox Code Playgroud)
最后,我现在可以在任何 TypeScript 代码中导入和使用我的配置变量。
// server/main.ts
import express from 'express';
import config from './config';
const { port } = config;
const app = express();
app.listen(port);
Run Code Online (Sandbox Code Playgroud)
这种方法有以下好处:
node-config
而无需重新发明轮子config.get
实用程序可用于获取配置值,如下所示:
import config from 'config';
const port: number = config.get('server.port');
Run Code Online (Sandbox Code Playgroud)
从以前开始,我仍然遇到config
无法server
从default.ts
.
下面是我如何使用 npm 配置模块。更新export default {
为export =
:
// default.ts
export = {
server: {
port: 4000,
},
logLevel: 'error',
};
Run Code Online (Sandbox Code Playgroud)
应用内使用 [相同]:
import config from 'config';
console.log(config.get('server'));
Run Code Online (Sandbox Code Playgroud)