Skip to content

Sapper: Support for preload function #497

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
dummdidumm opened this issue Aug 28, 2020 · 2 comments
Closed

Sapper: Support for preload function #497

dummdidumm opened this issue Aug 28, 2020 · 2 comments
Assignees
Labels
feature request New feature or request

Comments

@dummdidumm
Copy link
Member

dummdidumm commented Aug 28, 2020

Is your feature request related to a problem? Please describe.
Using sapper with the preload function inside module script gives a bad DX.

export async function preload(page, session) { // <------- not typed, need to add typings yourself
    const res = await this.fetch(`blog/${slug}.json`); // <--- error, what it `this`?
}

Describe the solution you'd like
Support typing for the preload function and for this, but in such a way that it will not also provide these for non-sapper-projects.

Notes / open questions

  • this probably needs to be transformed to some ambient global which has fetch defined on it.
  • preload is tricky because it's not a usage of something we can provide in the ambient context, but a definition . Not sure how to implement this.
  • How to only provide these typings/transformations in a Sapper project? How can we determine this? Look into the package.json?
@dummdidumm
Copy link
Member Author

After some more thought and hearing that the context is possibly user-modifiable in the future, I'm deciding against baking this into the language-tools.

  • getting arguments ambiently typed is not possible
  • typing this is possible to do by the user, and since it may be modified, our typings may be wrong anyway in the future

How to type this this (hah) then?

You can type the this context of a function explicitly in TypeScript (see docs):

     // Better move that into some file and do `import type { PreloadContext } from ...` to not type it every time
    interface PreloadContext {
        fetch: ...,
        ...
    }

    // won't work with export const preload = (...
    export async function preload(this: PreloadContext, ...page/session, if you need it) {
       ...
       this.fetch(...) // <-- works without type errors
    }

@dummdidumm
Copy link
Member Author

Fixed via sveltejs/sapper#1468

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature request New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant