matthewp / astro-fastify

A Fastify adapter for Astro
62 stars 16 forks source link

Example from README does not work #1

Closed nobleach closed 2 years ago

nobleach commented 2 years ago

I'm trying to decide if this is just a documentation issue or if there's something else going on. Starting a brand new Astro project via npm create astro@latest and then attempting to add this dependency, throws an error:

Cannot find module '/home/jim/Sites/ostk-header/api/index.js' imported from /home/jim/Sites/ostk-header/node_modules/@matthewp/astro-fastify/lib/index.js
Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/home/jim/Sites/ostk-header/api/index.js' imported from /home/jim/Sites/ostk-header/node_modules/@matthewp/astro-fastify/l
ib/index.js
    at new NodeError (node:internal/errors:393:5)

Well that's simple enough, right? We named the file api/index.ts. So, let's change that in the config:

import fastify from '@matthewp/astro-fastify';

/** @type {import('astro').AstroUserConfig} */
export default {
  output: 'server',
  adapter: fastify({
    entry: new URL('./api/index.ts', import.meta.url)
  })
};

But that'll throw:

Unknown file extension ".ts" for /home/jim/Sites/ostk-header/api/index.ts
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /home/jim/Sites/ostk-header/api/index.ts
    at new NodeError (node:internal/errors:393:5)
    at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:80:11)
    at defaultGetFormat (node:internal/modules/esm/get_format:122:38)

As we're trying to us ESM imports, not Typescript. So let's try naming the file index.js. From the presence of a type definition, it looks like you really did mean for it to be Typescript though. Regardless, that doesn't work.

Finally, let's name the file .mjs and change the reference to ./api/index.mjs. THAT seems to work. I don't think that was your intention though. I really do think you wanted to use Typescript so... what might I be missing here?

matthewp commented 2 years ago

To be fair, the readme shows using .js, not .ts. The reason TypeScript don't work here is that in development mode the entry is imported when the server is being configured and is imported directly from Node.js, not from within Vite. So you don't get any of Vite's features such as TS.

Since this file does wind up part of your build it would be better if this file were imported by Vite in dev mode. I'll have to see the practicality of doing that, but it's definitely a nice to have. Thanks for reporting!