Как экспортировать переменную Dynami c в TypeScript - PullRequest
0 голосов
/ 01 августа 2020

Я сейчас конвертирую код из 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);

У меня проблема с этим в машинописном тексте

Как я могу инициализировать переменную ключей только один раз, а затем иметь возможность import keys from './keys';

?

Спасибо!

Ответы [ 2 ]

2 голосов
/ 01 августа 2020

Я думаю, вам следует обернуть свой код ключами. 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();

и, возможно, вам следует переключиться на использование модуля esnext с синтаксисом import ... from ..., вы можете сделать это путем изменения tsconfig. json compilerOptions на "module": "esnext"

1 голос
/ 01 августа 2020

Не пробовал, но думаю:

let keys;
try {
  // eslint-disable-next-line security/detect-non-literal-fs-filename
  keys = JSON.parse(fs.readFileSync(credsPath, 'utf8'));
  if (keys) {
    logger.info('initKeysSuccess', 'keys ready', null);
  } else {
    logger.error('initKeysError', null, { credsPath });
  }
} catch (error) {
  logger.error('initKeysParseError', error, { credsPath });
}

export { keys };
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...