首页 > 解决方案 > 从 CommonJS 应用程序导出 const 并要求它们在另一个文件中

问题描述

我想const configconfig.jsCommonJs 应用程序中的文件导出。

const config = {
    development: {
        client: 'pg',
        connection: {
            database: 'myDatabase',
            user: 'myUser',
            host: 'localhost',
            password: 'password',
            port: PORT,
            ssl: {
                rejectUnauthorized: false
            }
        },
        server: {
            host: '127.0.0.1',
            port: 'PORT2'
        }
    }

module.exports = config;

index.js我需要这样

var env = process.env.NODE_ENV || 'development';
const config = require('./config')[env];

const knexDB = knex({
    client: config.client, 
    connection: {
        database: config.database,
        user: config.user,
        host: config.host,
        password: config.password,
        port: config.port,
        ssl: {
            rejectUnauthorized: false
        }
    }
});

但是在配置文件中。IntelliSense 建议更改为我不想做module.exports的 ES并保留应用程序 CommonJS。export另外,index.js 中的配置对象我有这个错误:

Property 'host' does not exist on type '{ development: { client: string; connection: { database: string; user: string; host: string; password: string; port: number; ssl: { rejectUnauthorized: boolean; }; }; server: { host: string; port: string; }; }; production: { ...; }; }'.ts(2339)

如何从 config.js 导出配置?

标签: javascriptnode.jscommonjs

解决方案


好吧,我找到了解决它的方法。connection我从中删除development并且它起作用了!只是提到我在连接中使用了config.connection.clientandconfig.development.connection.client或其他变量,但仍然无法在index.js. 所以看起来像

const config = {
    development: {
        client: 'pg',
        database: 'myDatabase',
        user: 'myUser',
        host: 'localhost',
        password: 'password',
        port: PORT,
        ssl: {
            rejectUnauthorized: false
        }
        server: {
            host: '127.0.0.1',
            port: 'PORT2'
        }
    }

module.exports = config;

index.js我访问那个

const configure = require('./config.js')[env];
const knexDB = knex({
    client: configure.client, 
    connection: {
        database: configure.database, 
        user: configure.user,
        host: configure.host,
        password: configure.password,
        port: configure.port,
        ssl: {
            rejectUnauthorized: false
        }
    }
});

感谢大家的贡献。


推荐阅读