skip to Main Content

I found this piece of code in github and I don’t understand it

function writeClients(dictionary: IReferenceDirectory[]) {
//more code here

  let superClientFile = `import IClientOptions from './base/IClientOptions';n`;
  superClientFile += `import Transport from './base/Transport';nn`;

source: https://github.com/Silind/twitter-api-client/blob/c8d724f38a9ed7112cd112ce11f2013f21b4740f/src/generator/writeClients.ts#L11

why don’t the author import at the most top? What’s the intention here? and he use += too

2

Answers


  1. Looks like the library dynamically builds the TwitterClient class with fields and methods depending on the passed dictionary argument. At the end of the referenced file, you can see that the generated class is written to disk:

    fs.writeFileSync(`${generatedPath}/index.ts`, superClientFile);
    

    So it seems that this is a fancy way of generating the TwitterClient that can later be imported in your app. Also building the class content using += concatenation is considered the way to go nowadays, see JS strings "+" vs concat method for more information.

    Login or Signup to reply.
  2. It imports the selected files based on clients.

    clients.forEach((client) => {
      superClientFile += `import ${client} from './clients/${client}';n`;
    });
    

    And at the end of the file, it writes the code into the file index.ts so above two import lines should be included in superClientFile string.
    That is the code of file – index.ts

    ...
    superClientFile += '}nnexport default TwitterClient;n';
    fs.writeFileSync(`${generatedPath}/index.ts`, superClientFile);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search