yargs: bundle with esbuild fails because `yargs/yargs` does not have file extension

Possible duplicate of #1929 but I’m not sure because that ticket is too vague.

esbuild determines content types based on file extension. esbuild docs

But yargs/yargs does not have a file extension.

This raises an error:

$ echo 'import createYargs from "yargs/yargs";' | yarn esbuild --bundle --loader=js
 > <stdin>:1:24: error: Do not know how to load path: node_modules/yargs/yargs
    1 │ import createYargs from "yargs/yargs";
      ╵                         ~~~~~~~~~~~~~

1 error

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 2
  • Comments: 15 (8 by maintainers)

Most upvoted comments

This is becoming a fatal error with Node 17.x where the top-level project is Node.js ESM (not TypeScript).

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension "" for /home/ubuntu/app/node_modules/.pnpm/yargs@17.3.1/node_modules/yargs/yargs
    at new NodeError (node:internal/errors:371:5)
    at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:84:11)
    at defaultGetFormat (node:internal/modules/esm/get_format:99: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 async ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:81:21)
 ```

Hello! I am here to share my solution. You can get around this error by using the following esbuild plugin: esbuild-plugin-alias With the plugin, you can alias some file call, like this: image

Keeping this file without an extension is a hack necessary to prevent yargs from treating the file as ESM, since for the benefit of TypeScript, the package.json is of type, module.

This can be fixed as soon as TypeScript supports a .mjs extension.

Do you have a link to the issues or PRs where this decision was discussed?

@cspotcode no, this design grew organically while trying to support both CJS and ESM in the same module.

The approach is discussed, without much detail, here.

Open to other approaches as long as all existing tests continue working, and we verify functionality on all supported Node runtimes.