首页 > 解决方案 > 如何在 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';

?

谢谢!

标签: node.jstypescript

解决方案


我认为,您应该将代码包装在 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"


推荐阅读