node.js - 如何在 TypeScript 中导出动态变量
问题描述
我目前正在将一些代码从 Node JavaScript 转换为 TypeScript
我有一个名为 keys.js 的文件
let keys;
try {
// eslint-disable-next-line security/detect-non-literal-fs-filename
keys = JSON.parse(fs.readFileSync(credsPath, 'utf8'));
} catch (error) {
return logger.error('initKeysParseError', error, { credsPath });
}
if (keys) {
logger.info('initKeysSuccess', 'keys ready', null);
return (module.exports.keys = keys);
}
return logger.error('initKeysError', null, { credsPath });
当我想keys
在另一个文件中使用时,我会
const { keys } = require('./keys');
console.log(keys.account.username);
我在打字稿中遇到了一些问题
我怎样才能只初始化一次 keys 变量然后就可以做
import keys from './keys';
?
谢谢!
解决方案
我认为,您应该将代码包装在 keys.js 中的某个函数中
exports.getKeys = function() {
let keys;
try {
// eslint-disable-next-line security/detect-non-literal-fs-filename
keys = JSON.parse(fs.readFileSync(credsPath, 'utf8'));
} catch (error) {
logger.error('initKeysParseError', error, { credsPath });
}
if (keys) {
logger.info('initKeysSuccess', 'keys ready', null);
return keys;
}
logger.error('initKeysError', null, { credsPath })
return keys;
}
const module = require('./keys.js')
const keys = module.getKeys();
也许你应该切换到使用带有import ... from ...
语法的 esnext 模块,你可以通过将 tsconfig.json compilerOptions 更改为"module": "esnext"
推荐阅读
- android - openfire ReconnectionManager java.lang.IllegalStateException
- nativescript - Nativescript Webpack5 - 如何从捆绑中排除目录、所有子目录和文件,然后复制到输出目录
- java - JSTL - 变量在中间包含空格
- vue.js - 笑话:TypeError:无法读取未定义的属性“变量”
- firebase - BT Web Protect 阻止 Firebase 存储 URL
- django - 尝试单击图像 url 时在 django localhost 中找不到 404 页面
- ios - 在 UserDefaults 中存储 OpaquePointer 类型
- email - 未显示带有 ical-event 的电子邮件正文
- ads - 在台式机或平板电脑中隐藏(Adsense-ads)代码的任何选项......?
- laravel - laravel 无法启动第一个项目