sveltejs / kit

web development, streamlined

Home Page:https://kit.svelte.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Ensure `.js` extensions are present with Typescript 5

mattjennings opened this issue · comments

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.

For anyone running into the issue for the meantime, I was able to get .js extensions added by installing ts-patch and using typescript-transform-extensions. Obviously not the ideal solution, but it will work for now.

There's a lot to unpack in that TS issue, but I kind of agree with their final decision. There's also a summary of that thread from microsoft/TypeScript#16577 (comment). I'm not sure what we should do for package as we are not doing any bundling step here, module resolution works as expected for almost everything else I know, except (which you mentioned) that Webpack template. Which makes me think that this should be resolved on Webpack's loader side. I'm also moving this to p2 for reasons that there's not a lot users that uses Svelte with Webpack, and it's plugin isn't as well maintained as Rollup or Vite.

Can you also elaborate how adding .js breaks usage within the kit project itself? What happens if you write it in index.js instead of index.ts? If that works, this might need to be resolved on Vite or the vite-plugin-svelte's side.

The reason .js imports won't work within the kit project itself is because that .js file doesn't exist yet (it will only be there post-compilation in the output folder). So if you run svelte-kit package, the .js file will exist in the output and that will all be fine when consumed. But if you're importing src/lib internally in your routes, since it's just .ts files, there won't be any .js file to import and vite will throw an error. This would go for any bundler, really.

Since ESM spec requires import extensions I think this could be another QoL thing package does for you even though it's a result of using typescript. However, like you said, rollup/vite handle this gracefully, so maybe it's fine to leave it up to the bundler. It's just a bit of extra burden on library maintainers using package to communicate this, even if the webpack + svelte userbase is low.

I don't understand. If I import src/libs in src/routes from the same project I don't experience any errors.

(Accidental close)

Ok I understand - you're stuck in an either-or situation. Either make it work for webpack, or work internally, but not both.

exactly yeah.

TypeScript doubled down on their approach and with TS 4.5 they introduce a new resolution mode, node12/nodenext which when enabled requires people to import files with full specifiers, using .js if you import .ts files. To me this means that this issue will likely solve itself sooner than later because other tools like Vite etc have to adjust to this.

Vite has plans to support importing .js in .ts files soon according to vitejs/vite#3040 (comment)

According to their changelog this is scheduled to release in a few days when 2.7 is out https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md

Mhm TS 4.5 reversed adding ESM support through a flag due to having concerns about it: microsoft/TypeScript#46452
Not sure how this affects resolving this ticket.

hey @dummdidumm @mattjennings what's your current approach on this?
We're running into the same issue when trying to build packages.

Example:

//./TestClass.ts
export default class TestClass {
  ...
}
//index.ts
export {default as TestClass} from './TestClass'

Becomes this after build:

//TestClass.js
export default class TestClass {
    ...
}
//index.js
export {default as TestClass} from './TestClass'

And it errors with:

import {TestClass} from 'test-package';
        ^^^^^^^^^
SyntaxError: The requested module 'test-package' does not provide an export named 'TestClass'

So basically, it can't be read in ESM without the .js extension as in export {default as TestClass} from './TestClass.js'

I'd love to help find a solution, as this basically prevents to build a simple package when using typescript with the package command :)

Or are there any known workarounds?

What about importing with .js in your source code?

//index.ts
export {default as TestClass} from './TestClass.js'

I don't think the package command should be prepending imports with .js. That sounds very risky.

Well, those are typescript files, that are then transpiled to js when running the package command @bluwy.

so that’s actually where tue issue comes from, everything is sveltekits default typescript and that’s I guess how it should be, but when running package, either I have remaining .ts endings or none and both don’t work.

as a workaround we added all .ts extensions and after package we manually replace them with .js
Kinda ugly :)

So when using package command and the library is ts based, how is this intended to work?
The files get transpiled to js, but the references / import statements aren’t, so when importing the package later on it fails.

Maybe I’m missing a point here.

Hmm. I thought you can import .ts files with a .js extension? Vite already supports that. But I could be missing a point here too 😄

The problem is TypeScript<->Svelte: It doesn't rewrite import paths (doesn't append a .js). There's the experimental module: node12 setting which would make TypeScript shut up when such a ending is present (right now it errors), but that module setting is only available in nightlies right now. So right now we're in this limbo state where TS doesn't fully support the new ESM resolution style yet, but you need to use it as part of SvelteKit because we decided to go ESM since it's the new standard and therefore futureproof. Until TS makes this non-experimental workarounds like the one you mention (rewriting import paths) are the best solution.

I'd love to help find a solution, as this basically prevents to build a simple package when using typescript with the package command :)

Or are there any known workarounds?

Using ts-patch with typescript-transform-extensions was the easiest workaround I found. I use it for svelte-modals if you want to see how it looks in practice.

I haven't looked into this module: node12 thing but it sounds promising, hopefully that finds its way into a stable release soon.

Looks like TS 4.7 will finally have the nodenext/whatever setting which will enforce/allow the .js ending which should fix this

We've now upgraded to TypeScript 4.7 and we can use node16/nodenext now.

People authoring packages can solve this now by using node 16 / nodenext. They need to change the following settings in their tsconfig.json:

{
  "compilerOptions": {
    // ...
    "moduleResolution": "nodenext"
  }
}

Support for this will land in the next release of Svelte language-tools, I'll update this message once it's released.

I don't think we should change this setting for all users to this though, because then everyone is required to adhere to the new node resolution rules (which means explicit file endings for relative imports), not just package authors.
I therefore think we need another option in create-svelte which let's you chose if you want to create a package or an app. This would also solve the confusion around "what's this package command in my scripts, and why does it prompt me to install other stuff first in order to use it?"

Using "moduleResolution": "NodeNext", I have an error with import { page } from '$app/stores':

Cannot find module $app/stores or its corresponding type declarations.

Do you know how I can fix this while still using "moduleResolution": "NodeNext"?

Importing .ts utility files while specifying .js crashes the commands vite dev, vite build and vite preview. I can hide them behind an index.ts file and that sometimes seems to work fine, but it'd be nice to not have to do that since we then have to keep updated that index.ts manually.

Could you create a new issue for this with a reproduction?

I'm not sure that "moduleResolution": "Node16" is the best for us in the long run. Many people will be confused by that. I wonder if it's worth the trouble to use the transform API of ts.transpileModule to modify the relative imports of all Svelte/JS/TS files and rewrite them so that they satisfy the strict node resolution.

TypeScript will (in 5.0? don't know) ship more fine grained module resolution flags, which hopefully solve this issue.

We set NodeNext for libraries now:

See also #12163