egoist / tsup

The simplest and fastest way to bundle your TypeScript libraries.
https://tsup.egoist.dev
MIT License
9.18k stars 220 forks source link

bug: Unknown file extension `.json` in 6.x #646

Open ihmpavel opened 2 years ago

ihmpavel commented 2 years ago

Hi, thank you for the library.

I came into an issue while updating to version 6.

Code (index.ts)

  const dir = './xyz'
  const realPath = relative(
    __dirname,
    fs.realpathSync(join(dir, 'file.json'))
  )
  const { default: content } = await import(realPath)
  console.log(content)

Working fine

With version 6.x after reading release notes I though, that I need to add --shims (not mentioned in docs, only on release page) to build command (because we are using __dirname). Unfortunately that is not the case.

Does not work fine

Issue on version 6.x

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".json" for /Users/***********/xyz/file.json
    at new NodeError (node:internal/errors:371:5)
    at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:87:11)
    at defaultGetFormat (node:internal/modules/esm/get_format:102:38)
    at defaultLoad (node:internal/modules/esm/load:21:14)
    at ESMLoader.load (node:internal/modules/esm/loader:359:26)
    at ESMLoader.moduleProvider (node:internal/modules/esm/loader:280:58)
    at new ModuleJob (node:internal/modules/esm/module_job:66:26)
    at ESMLoader.#createModuleJob (node:internal/modules/esm/loader:297:17)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:261:34)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  code: 'ERR_UNKNOWN_FILE_EXTENSION'
}

Is there any way of fixing this?

Upvote & Fund

Fund with Polar

egoist commented 2 years ago

tsup won't bundle import(realPath) cause realPath is unknown at build time, you should manually read the file and JSON.parse it.

egoist commented 2 years ago

In v5 import() is compiled to require(), (the default target is node12) so require('xxx.json') worked, but now the target is node14, so import() is left as is, import('xxx.json') in Node.js runtime is not a thing.