Skip to content

Ensure .js extensions are present with Typescript 5 #205

@mattjennings

Description

@mattjennings

Describe the problem

This is a Typescript problem (see this, and this), but package is affected by this because it produces ESM javascript.

Say your src/lib folder has two files in it: index.ts and store.ts. Your index.ts looks like this:

export { myStore } from './store'

When you compile with svelte-kit package, the result is this:

export { myStore } from './store'

Because there's no .js file extension, this is will likely fail in ESM. SvelteKit projects seem to handle this fine (I'm not sure why), but projects using webpack for example will fail with the following error:

Module not found: Error: Can't resolve './store' in 'node_modules/your-lib'
Did you mean 'store.js'?
BREAKING CHANGE: The request './store' failed to resolve only because it was resolved as fully specified
(probably because the origin is a '*.mjs' file or a '*.js' file where the package.json contains '"type": "module"').
The extension in the request is mandatory for it to be fully specified.
Add the extension to the request.

Describe the proposed solution

Frustratingly, it seems Typescript's stance on this is to add .js to your file extensions in your .ts files. This works when compiling through package, but will not work if you want to consume src/lib yourself within the kit project (i.e under /routes, if you wanted to set up docs or something).

The only way around this that I can think of is to add .js extensions in a post-compilation script. Similar to how tsc-esm does it. It's dumb that kit has to care about this, but I think it's going to be a common gotcha for many library authors otherwise.

Alternatives considered

  • Compiling to commonjs but... no thanks

Importance

would make my life easier

Additional Information

In that tsc-esm package, it uses a utility file from grubber to add the .js extensions. I wrote up a script and ran it against my package output:

import patchJsImports from '@digitak/grubber/library/utilities/patchJsImports.js'

patchJsImports('./package')

and it worked on everything except my index.js file, but I haven't looked much further into that.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions