Skip to content

Instantly share code, notes, and snippets.

@ammuench
Created February 25, 2024 17:57
Show Gist options
  • Save ammuench/ce4d3130a4de12de5b7c8bb63d223dc8 to your computer and use it in GitHub Desktop.
Save ammuench/ce4d3130a4de12de5b7c8bb63d223dc8 to your computer and use it in GitHub Desktop.
Setup your Package.json to properly export types for require and import

Explanation of Issue

I'd been fighting this issue on my own package for the last few days:

Could not find a declaration file for module 'contrastrast'. '/home/Development/bookthing.nuxt/node_modules/.pnpm/[email protected]/node_modules/contrastrast/dist/contrastrast.js' implicitly has an 'any' type.
  There are types at '/home/Development/bookthing.nuxt/node_modules/contrastrast/dist/index.d.ts', but this result could not be resolved when respecting package.json "exports". The 'contrastrast' library may need to update its package.json or typings.

After lots of searching, I think I've settled on a solution that works for me at least in the short term.

Previously, my "exports" statement in my package.json looked like this:

"exports": {
  ".": {
    "import": "./dist/contrastrast.js",
    "require": "./dist/contrastrast.umd.cjs"
  }
},
"types": "./dist/index.d.ts",

Types was just a standalone file all on it's own.

However, with a later version of typescript (I think someone said it was 4.7 and later? Don't quote me on that, just hope it helps if you're stuck), the issue comes up with node modules using the "bundler" resolutoin available in later versions of Node (I think it came standard in v21 and later? agian don't quote me)

SOLUTION

Update your exports in package.json to look like this:

  "exports": {
    ".": {
      "import": {
        "default": "./dist/contrastrast.js",
        "types": "./dist/index.d.ts"
      },
      "require": {
        "default": "./dist/contrastrast.umd.cjs",
        "types": "./dist/index.d.cts"
      }
    }
  },

NOTE You'll also need to generate an index.d.cts file to accompany your index.d.ts file. You'll have to figure that out on your own depnding on your build step.

SHOUT OUT

Huge shoutout to Andrew Branch for creating the Are the types wrong CLI tool. Was super helpful in getting things kinda back in working order. Give them some praise!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment