honojs / honox

HonoX - Hono based meta framework
https://hono.dev
MIT License
1.41k stars 39 forks source link

'module is not defined' error when using prisma in basic hono-x template #101

Closed neutrino2211 closed 6 months ago

neutrino2211 commented 6 months ago

What version of HonoX are you using?

0.1.4

What steps can reproduce the bug?

$ npx create-hono@latest
$ npm install prisma --save-dev
$ npx prisma init --datasource-provider sqlite
model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
}
$ npx prisma migrate dev --name init
import { css } from 'hono/css'
import { createRoute } from 'honox/factory'
import Counter from '../islands/counter'
import {PrismaClient} from '@prisma/client'

const className = css`
  font-family: sans-serif;
`

export default createRoute(async (c) => {
  const name = c.req.query('name') ?? 'Hono'

  const prisma = new PrismaClient()
  await prisma.$connect();

  const users = await prisma.user.count();
  return c.render(
    <div class={className}>
      <h1>Hello, {name}! ${users}</h1>
      <Counter />
    </div>,
    { title: name }
  )
})

What is the expected behavior?

Expected behaviour is to have the index page contain a h1 with "Hello, Hono! 0". 0 denoting the number of user documents in the database.

What do you see instead?

An err module is not defined

Screenshot 2024-02-28 at 13 04 30

Additional information

I'm pretty sure it is an error with parsing commonjs modules but using @originjs/vite-plugin-commonjs does not really fix the issue and introduces the following error.

Screenshot 2024-02-28 at 13 09 34
BasWilson commented 6 months ago

@neutrino2211 You should externalise prisma in the vite config (Not sure what the exact package name is for prisma)

Reference

Something like this:

import pages from '@hono/vite-cloudflare-pages'
import honox from 'honox/vite'
import { defineConfig } from 'vite'

export default defineConfig(({ mode }) => {
  if (mode === 'client') {
    return {
      build: {
        rollupOptions: {
          input: ['/app/style.css'],
          output: {
            assetFileNames: 'static/assets/[name].[ext]'
          }
        }
      }
    }
  } else {
    return {
      ssr: {
        external: ['prisma']
      },
      plugins: [honox(), pages()]
    }
  }
})
neutrino2211 commented 6 months ago

Great, thanks. It's all working now!!

yusukebe commented 6 months ago

@BasWilson Thanks for the support!

Yeah, we have to add it to ssr.external if that throws the error.