将我的
config
模块导入到 ./index.ts
后,config
始终是未定义的。我正在绕圈子试图弄清楚这一点。非常感谢任何建议。
干杯!
这是我的文件结构:
config/
index.ts
development.ts
testing.ts
production.ts
index.ts
代码
config/index.ts
:
import { config as developmentConfig } from './development';
import { config as testingConfig } from './testing';
import { config as productionConfig } from './production';
interface Config {
host?: string;
port?: number;
dbName?: string;
dbUser?: string;
dbPassword?: string;
databaseUrl?: string;
}
const env: string = process.env.NODE_ENV || 'development';
const configuration: { [key: string]: Config } = {
development: developmentConfig,
testing: testingConfig,
production: productionConfig,
}
export const config: Config = configuration[env] || {}
代码
config/development.ts
:
import * as dotenv from "dotenv";
dotenv.config();
export const config = {
host: process.env.HOST || 'localhost',
port: parseInt(process.env.PORT!, 10) || 3000,
dbName: process.env.NAME || 'my-app',
dbUser: process.env.USER || 'my-username',
dbPassword: process.env.PASSWORD || '',
databaseUrl: process.env.DATABASE_URL || 'mongodb://localhost:27017/my-app',
};
config/testing.ts
和 config/production.ts
与 config/development.ts
几乎相同
代码
./index.ts
:
import pool from './src/pool';
import app from './src/app';
import { config } from './config';
console.log(config.databaseUrl); // config is undefined
console.log(config.dbName);
console.log(config.dbPassword);
console.log(config.dbUser);
console.log(config.host);
console.log(config.port);
const host = config.host;
const port = config.port;
const database = config.dbName;
const user = config.dbUser;
const password = config.dbPassword;
pool
.connect({
host,
port,
database,
user,
password
})
.then(() => {
app().listen(3005, () => {
console.log('Listening on port 3005');
});
})
.catch((err) => console.error(err));
你的代码看起来不错,我想问题可能是这样的
const env: string = process.env.NODE_ENV || 'development';
如果您将 NODE_ENV 设置为“测试”(写错),则不会回退到“开发”,并且会尝试查找不存在的密钥。这是我此时唯一看到的。