javascript - 从 CommonJS 应用程序导出 const 并要求它们在另一个文件中
问题描述
我想const config
从config.js
CommonJs 应用程序中的文件导出。
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 导出配置?
解决方案
好吧,我找到了解决它的方法。connection
我从中删除development
并且它起作用了!只是提到我在连接中使用了config.connection.client
andconfig.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
}
}
});
感谢大家的贡献。
推荐阅读
- java - 使用 Java 创建一个将 Int 转换为 String 的方法
- c# - 如何避免 MVC5 + Identity 中的会话劫持?/ 使cookie服务器端无效
- python - pythonw - 无法导入大多数(如果不是全部)站点包,甚至一些内置模块
- python - 当我输入 3 时,我得到打印 4 次的结果。你能告诉我为什么会这样吗?我是 python 新手
- python - 在类范围内导入模块的类型提示
- c++ - 如何调试 WebKit2GTK+ 扩展
- php - Nginx cors 启用 html 文件不起作用
- adobe - InDesign - 用于查找尖括号之间的特定单词并将其复制到列表中的脚本
- php - 如何修复'PHP代码在laravel公用文件夹中不起作用'
- python - 如何根据Python中的起始行和结束行获取类的范围?