Home > database >  how to load a js config file in a typescript npm package that will only be written in the future by
how to load a js config file in a typescript npm package that will only be written in the future by

Time:09-22

I'm trying to code in Typescript an NPM package that should work as a CLI tool.

For simplicity, let's say that the package will take the default export from a config.js file written by the dev using the package and print it in the console.

So the dev will:

  1. create a config.js file with export default 'hello world'
  2. type npx someLibrary and see "hello world" in the terminal.

This use case is common in tools I've used like babel, jest, and webpack. Although I've already overcome some technical challenges around that, I am stuck in how to grab the future config.js file in Typescript.

The approach I'm trying to pursue is using dynamic imports. The compiler won't allow it, since the config file doesn't exist at coding time. The code is something like this:

main();

async function main(): Promise<void> {
  const config = await import("./config.js");
  console.log(config);  
}

This causes the compiler error: Cannot find module './config.js' or its corresponding type declarations.ts(2307).

My question is: how can I tell typescript to import the config file that will be created in the future and be available only during runtime?

If that is impossible, how can I consume the content of that config file inside the Typescript program?

CodePudding user response:

My question is: how can I tell typescript to import the config file that will be created in the future and be available only during runtime?

a. For a quick solution, you can simply put @ts-ignore on the line above your import. This should ignore the compilation error, and at runtime the file should be imported accordingly.

b. Alternatively you may also use require('./config.js') instead of using import. This should also get rid of the compilation error.

c. For a more proper solution, you can look into using a function to read the file at runtime. Two things you can consider using are fetch and fs

fetch

fetch('./config.js')
  .then(response => response.text())
  .then(text => console.log(text))

fs

import fs from 'fs'
const data = fs.readFileSync('./config.js', 'utf8')
console.log(data)
  • Related