0

How can I read the configuration file (e.g. mypkg.config.ts) from the root of the project in my npm module built on ESM?

I found this, and figured out how to do it for .json, but not for .ts.

LIMPIX64
  • 201
  • 1
  • 3
  • 12

1 Answers1

0

After a few hours of searching, I found what I needed in the sources of Vite.

All you have to do is convert your configuration file into JavaScript using esbuild for example, and then import it using:

const config = await import(`file://${absolutePathToTranspiledConfig}`)

And then just delete the generated JavaScript file.

Specifically, Vite uses the following transpilation script:

await build({
  entryPoints: [/*path to config with .ts extension*/],
  bundle: true,
  minify: true,
  platform: 'node',
  outfile: /*path to transpiled config*/,
  sourcemap: 'inline',
  metafile: true,
  format: 'esm',
  plugins: [
    {
      name: 'externalize-deps',
      setup(build) {
        build.onResolve({ filter: /.*/ }, args => {
          const id = args.path
          if (id[0] !== '.' && !path.isAbsolute(id)) {
            return {
              external: true
            }
          }
        })
      }
    },
    {
      name: 'replace-import-meta',
      setup(build) {
        build.onLoad({ filter: /\.[jt]s$/ }, async args => {
          const contents = await fs.readFile(args.path, 'utf8')
          return {
            loader: args.path.endsWith('.ts') ? 'ts' : 'js',
            contents: contents
              .replace(
                /\bimport\.meta\.url\b/g,
                JSON.stringify(`file://${args.path}`)
              )
              .replace(
                /\b__dirname\b/g,
                JSON.stringify(path.dirname(args.path))
              )
              .replace(/\b__filename\b/g, JSON.stringify(args.path))
          }
        })
      }
    }
  ]
})
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
LIMPIX64
  • 201
  • 1
  • 3
  • 12