Code Monkey home page Code Monkey logo

fastify-vite's Introduction


@fastify/vite

This Fastify plugin allows you to run Vite's development server as middleware, expose your Vite application to your Fastify application, with configuration hooks to ease router integration and other customizations, and also automatically serve Vite builds, inferred from a Vite configuration file.

See the full documentation suite to learn more.

fastify-vite's People

Contributors

10xlacroixdrinker avatar ajaishankar avatar alex4o avatar benatshippabo avatar cesar-m-diaz avatar davidmeirlevy avatar fdawgs avatar felixmosh avatar galvez avatar gehbt avatar ilyasemenov avatar jatindotdev avatar jens-ox avatar kwiniarski avatar matt-smarsh avatar micheleriva avatar mr-xiayang avatar mrbazlow avatar paul-isache avatar predokmif avatar rafaelgss avatar romain-trotard avatar rtritto avatar shriah avatar shyam-chen avatar svmak avatar sync avatar tomashco avatar tylervick avatar yonathan06 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fastify-vite's Issues

fastify-vite server is not esbuild friendly

Problem

fastify-vite server is not esbuild friendly, meaning that it's not possible to build it with esbuild into a single redistributable script.

To my thinking, this is a shame given that the project itself relies on vite/esbuild, but is not following its best practices.

Steps to reproduce

Take examples/vue-api from the dev branch, and run:

yarn esbuild server.js --bundle --platform=node --outfile=dist/server.js

you will get lots of errors of "Could not resolve" errors. When you resolve all of them, you'll end up with:

yarn esbuild server.js --bundle --platform=node --outfile=dist/server.js --external:consolidate --external:vite/dist/client/client.js --external:vite/dist/client/env.js --external:rollup  --external:acorn

if you run it, you will get:

❯ node dist/server.js
/Users/semenov/gh/fastify-vite/examples/vue-api/dist/server.js:30287
        throw new Error(`The esbuild JavaScript API cannot be bundled. Please mark the "esbuild" package as external so it's not included in the bundle.
              ^

Error: The esbuild JavaScript API cannot be bundled. Please mark the "esbuild" package as external so it's not included in the bundle.

now if you also add esbuild to externals, you'll get a build which will not run without node_modules:

❯ node dist/server.js
node:internal/modules/cjs/loader:943
  throw err;
  ^

Error: Cannot find module 'esbuild'
Require stack:
- /Users/semenov/gh/fastify-vite/examples/vue-api/dist/server.js

Suggestions

The library should be refactored to allow tree shaking to work:

  • fastify-vite must export two fastify plugins: one for dev mode and one for production, and let the user decide which to run based on whatever logic they prefer, such as based on process.env.NODE_ENV. You may also continue to export the default implementation which follows the current logic of looking into options.dev - but it must be tree shakeable.
  • Same goes for fastify-vite-vue, there must be two separate renderers, so that in production mode vite.ssrLoadModule is excluded by tree shaking.
  • Magic build mode should be provided not by fastifyVite.app (a property on function! completely non tree-shakeable) but by a separately exported function.
  • getViteOptions should probably not be used at all. After all, with fastify-vite, vite.config.js is half broken anyway (e.g. one must remove @vitejs/plugin-vue from plugins, or face cryptic errors). Let the user import it manually and feed to fastify.register(fastifyVite, { vite }), it's not a big deal.

Other notes

I'm currently using https://github.com/frandiox/vite-ssr which works fine with esbuild. Their approach is different - they use a binary script for dev mode (vite-ssr), and no helpers at all for production mode. (For example, this is the suggested boilerplate for Express production server.)

They however lack useServerData so I was looking for alternatives.

[Solid] Solid example is not working

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

3.27.4

Plugin version

No response

Node.js version

16.14.0

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

PopOS 21.10

Description

Hello,
I want to use fastify vite for a solid js application. But I don't know why but it seems fastify-vite is incompatible with solid-app-router. As I see maybe there is an invalid configuration who display this error :

❯ pnpm dev                                

> [email protected] dev /home/quentin/Documents/dev/fastify-solid
> ts-node-dev --no-notify --respawn --transpile-only ./src/app.ts

[INFO] 08:33:43 ts-node-dev ver. 1.1.8 (using ts-node ver. 9.1.1, typescript ver. 4.6.3)
8:33:44 AM [vite] Error when evaluating SSR module @app/client.jsx:
file:///home/quentin/Documents/dev/fastify-solid/node_modules/.pnpm/[email protected][email protected]/node_modules/solid-app-router/dist/index.js:1
import { isServer, template, createComponent as createComponent$1, mergeProps, spread, insert, effect, setAttribute } from 'solid-js/web';
                                                                                               ^^^^^^
SyntaxError: The requested module 'solid-js/web' does not provide an export named 'effect'
    at ModuleJob._instantiate (node:internal/modules/esm/module_job:127:21)
    at ModuleJob.run (node:internal/modules/esm/module_job:191:5)
    at async Promise.all (index 0)
    at ESMLoader.import (node:internal/modules/esm/loader:337:24)
    at importModuleDynamicallyWrapper (node:internal/vm/module:437:15)
    at nodeImport (/home/quentin/Documents/dev/fastify-solid/node_modules/.pnpm/[email protected]/node_modules/vite/dist/node/chunks/dep-9c153816.js:56262:21)
    at eval (@app/client.jsx:14:31)
    at instantiateModule (/home/quentin/Documents/dev/fastify-solid/node_modules/.pnpm/[email protected]/node_modules/vite/dist/node/chunks/dep-9c153816.js:56193:9)
8:33:44 AM [vite] Error when evaluating SSR module /home/quentin/Documents/dev/fastify-solid/src/@app/entry/server.jsx:
file:///home/quentin/Documents/dev/fastify-solid/node_modules/.pnpm/[email protected][email protected]/node_modules/solid-app-router/dist/index.js:1
import { isServer, template, createComponent as createComponent$1, mergeProps, spread, insert, effect, setAttribute } from 'solid-js/web';
                                                                                               ^^^^^^
SyntaxError: The requested module 'solid-js/web' does not provide an export named 'effect'
    at ModuleJob._instantiate (node:internal/modules/esm/module_job:127:21)
    at ModuleJob.run (node:internal/modules/esm/module_job:191:5)
    at async Promise.all (index 0)
    at ESMLoader.import (node:internal/modules/esm/loader:337:24)
    at importModuleDynamicallyWrapper (node:internal/vm/module:437:15)
    at nodeImport (/home/quentin/Documents/dev/fastify-solid/node_modules/.pnpm/[email protected]/node_modules/vite/dist/node/chunks/dep-9c153816.js:56262:21)
    at eval (@app/client.jsx:14:31)
    at instantiateModule (/home/quentin/Documents/dev/fastify-solid/node_modules/.pnpm/[email protected]/node_modules/vite/dist/node/chunks/dep-9c153816.js:56193:9)
file:///home/quentin/Documents/dev/fastify-solid/node_modules/.pnpm/[email protected][email protected]/node_modules/solid-app-router/dist/index.js:1
import { isServer, template, createComponent as createComponent$1, mergeProps, spread, insert, effect, setAttribute } from 'solid-js/web';
                                                                                               ^^^^^^
SyntaxError: The requested module 'solid-js/web' does not provide an export named 'effect'
    at ModuleJob._instantiate (node:internal/modules/esm/module_job:127:21)
    at ModuleJob.run (node:internal/modules/esm/module_job:191:5)
    at async Promise.all (index 0)
    at ESMLoader.import (node:internal/modules/esm/loader:337:24)
    at importModuleDynamicallyWrapper (node:internal/vm/module:437:15)
    at nodeImport (/home/quentin/Documents/dev/fastify-solid/node_modules/.pnpm/[email protected]/node_modules/vite/dist/node/chunks/dep-9c153816.js:56262:21)
    at eval (@app/client.jsx:14:31)
    at instantiateModule (/home/quentin/Documents/dev/fastify-solid/node_modules/.pnpm/[email protected]/node_modules/vite/dist/node/chunks/dep-9c153816.js:56193:9)
[ERROR] 08:33:44 SyntaxError: The requested module 'solid-js/web' does not provide an export named 'effect'

I see an issue who have the same error : solidjs/solid-router#80

Steps to Reproduce

I give a reproduction repository : https://github.com/qlaffont-flexper/fastify-solid-vite-example

Expected Behavior

No response

unocss not work

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.2.1

Plugin version

3.0.0-beta.23

Node.js version

16.x

Operating system

Windows

Operating system version (i.e. 20.04, 11.3, 10)

10

Description

unocss not work when add class in page element.

Steps to Reproduce

<h1 class="text-hex-333">{{ message }}</h1>

Expected Behavior

No response

How to write a test for Vue3 SFC components ?

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

Hi There.

I'd like to write unit tests for my Vue3 SFC components in my fastify-vite app.
I tried to use:

  • "@babel/preset-env": "^7.16.11",
  • "@vue/test-utils": "^2.0.0-rc.18",
  • "@vue/vue3-jest": "^27.0.0-alpha.4",
  • "babel-core": "^7.0.0-bridge.0",
  • "babel-jest": "^27.4.6",
  • "jest": "^27.4.7",

My jest.config.json looks like

module.exports = {
    moduleFileExtensions: ['js', 'json', 'vue'],
    testEnvironment: 'jsdom',
    transform: {
        '^.+\\.js$': 'babel-jest',
        '^.+\\.vue$': '@vue/vue3-jest'
    }
};

And my copyright.spec.js file looks

import {shallowMount} from '@vue/test-utils';
import Copyright from '../../../pageComponents/base/copyright.vue';

describe('Page components / Base / Copyright', () => {
    it('should have correct text', () => {
        const copyrightText = `My copyright text`;
        const wrapper = shallowMount(Copyright);

        expect(wrapper.text()).toContain(copyrightText);
    });
});

When I run tests, I see an error

TypeError: (0 , _vue.createElementVNode) is not a function

Could you please recommend me, how to fix it ? Maybe you have a working example, how to write tests for Vue3 components in fastify-vite apps ?

Thank you.

React support

This is a great addition to the Fastify ecosystem. Would you be interested to support React in addition to Vue?

Windows clientModule returning null

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

3.29.0

Plugin version

3.0.0-beta.21

Node.js version

16.15.1

Operating system

Windows

Operating system version (i.e. 20.04, 11.3, 10)

10

Description

When running vue-stream example on Windows we receive an error:

TypeError: Cannot read properties of null (reading 'replace')

this comes from the following line in node_modules/fastify-vite/mode/development.js

const modulePath = resolve(config.vite.root, config.clientModule.replace(/^\/+/, ''))

it looks like the root of the client is returning null. On linux this same app works fine.

In order to fix this on Windows I changed the root in vite config to a relative path (i.e. "./client"). And in package.json, I change the "build:server" file to "./index.js"

After changing to relative urls, when I start the server I get

Error [ERR_UNSUPPORTED_ESM_URL_SCHEME]: Only URLs with a scheme in: file, data are supported by the default ESM loader. On Windows, absolute paths must be valid file:// URLs. Received protocol 'c:'

It may be related to this issue nodejs/node#37845

Steps to Reproduce

Copy vue-stream example to a windows machine and try to use

Expected Behavior

No response

Improved Docs for newbies to Vite and mjs

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

🚀 Feature Proposal

Hi there!

I have a couple of thoughts about getting started.

  1. It's worth putting into the docs "type": "module" - It's a bit embarrassing but I didn't even know node.js supported this! Amazing.
  2. It would be good to explain import.meta.url - I have never seen this before and it's hard to google.
  3. Using the default React guide and view renders 404 when you try it (even after type.module is set in package.json (it would be good if this worked out of the box - I still haven't got it working 😓
  4. Instructions on how to use fastify-cli for automatic server restarts based on watching files.

I see the potential in this project but it's hard for people to get started still (with the React version) and it may put people off!

Thank you for all the work so far!

J

Motivation

I want the initial setup experience for newcomers to be really easy.

Example

It's a documentation thing.

Server HMR

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

🚀 Feature Proposal

Are there plans for server HMR?

Motivation

I could use nodemon, but it restarts the vite server every change. It would be nice to be able to get hmr on the server as well.

Example

yarn dev would hmr on client and server

process.exit() will exit with code 13

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

3.x

Plugin version

3.x

Node.js version

16.x

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

11.0.1

Description

As uncovered by #65, process.exit() is incorrectly exiting with exit code 13.

This probably means we're exiting in an unsafe one — we should probably do app.close() before.

Steps to Reproduce

Run process.exit() after Fastify server started.

Expected Behavior

Exit code 0

createComponentInstance error in dev mode

There is this error in the browser in dev mode:

Uncaught TypeError: Cannot destructure property 'createComponentInstance' of 'vue.ssrUtils' as it is null.
    at node_modules/@vue/server-renderer/dist/server-renderer.cjs.js (server-renderer.cjs.js:126)
    at __require2 (chunk-OX5HPUJB.js?v=e457d9ce:44)
    at node_modules/@vue/server-renderer/index.js (index.js:6)
    at __require2 (chunk-OX5HPUJB.js?v=e457d9ce:44)
    at node_modules/fastify-vite-vue/render.js (render.js:1)
    at __require2 (chunk-OX5HPUJB.js?v=e457d9ce:44)
    at node_modules/fastify-vite-vue/server.js (server.js:2)
    at __require2 (chunk-OX5HPUJB.js?v=e457d9ce:44)
    at dep:fastify-vite-vue_server:1

So, HMR is broken.
I followed each steps in the quick start guide.
I also tried with degit terixjs/fastify-vite/examples/vue-base my-app but with same issue.

My config:

System Version: macOS 10.15.6 (19G2021)
node.js: v14.17.1
npm: 7.24.2

Potentials related solutions: (but those are for Webpack, and Vite use Rollup?)
vuejs/core#3379
https://stackoverflow.com/questions/64324714/typeerror-cannot-destructure-property-createcomponentinstance-of-vue-ssrutil

Simple Getting started has errors

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

3.25.3

Plugin version

3.0.0

Node.js version

16.13.1

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

11.6 (Big Sur)

Description

I followed the instructions in https://fastify-vite.dev/quickstart/vue.html but on trying to execute node app.mjs I get errors that ./symobls.js is not found. Looking at the source in node_modules/fastify-vite-vue/app.js is looks like the code is:

const {
  kData,
  kPayload,
  kGlobal,
  kAPI,
  kIsomorphic,
  kFirstRender,
} = require('./symbols.js')

But there appears to be no file symbols.js in node_modules/fastify-vite-vue

Steps to Reproduce

~/NodeProjects/ViteFastify ❱ mkdir simple
~/NodeProjects/ViteFastify ❱ cd simple
NodeProjects/ViteFastify/simple ❱ npm i fastify fastify-vite fastify-vite-vue --save

added 215 packages, and audited 216 packages in 19s

24 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

NodeProjects/ViteFastify/simple ❱ code ./../simple

<added the minimal files as per instructions>

NodeProjects/ViteFastify/simple ❱ node app.mjs                                                                                                 ⬢ v16.13.1 via 🅒 node-env-16.3.1
4:37:59 PM [vite] Error when evaluating SSR module @app/client.js:
Error: Cannot find module './symbols.js'
Require stack:
- /Users/jason/NodeProjects/ViteFastify/simple/node_modules/fastify-vite-vue/app.js
- /Users/jason/NodeProjects/ViteFastify/simple/node_modules/fastify-vite-vue/routing.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.<anonymous> (/Users/jason/NodeProjects/ViteFastify/simple/node_modules/vite/dist/node/chunks/dep-76613303.js:60126:20)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (/Users/jason/NodeProjects/ViteFastify/simple/node_modules/fastify-vite-vue/app.js:12:5)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
4:37:59 PM [vite] Error when evaluating SSR module /Users/jason/NodeProjects/ViteFastify/simple/@app/entry/server.js:
Error: Cannot find module './symbols.js'
Require stack:
- /Users/jason/NodeProjects/ViteFastify/simple/node_modules/fastify-vite-vue/app.js
- /Users/jason/NodeProjects/ViteFastify/simple/node_modules/fastify-vite-vue/routing.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.<anonymous> (/Users/jason/NodeProjects/ViteFastify/simple/node_modules/vite/dist/node/chunks/dep-76613303.js:60126:20)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (/Users/jason/NodeProjects/ViteFastify/simple/node_modules/fastify-vite-vue/app.js:12:5)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
node:internal/process/esm_loader:94
    internalBinding('errors').triggerUncaughtException(
                              ^

Error: Cannot find module './symbols.js'
Require stack:
- /Users/jason/NodeProjects/ViteFastify/simple/node_modules/fastify-vite-vue/app.js
- /Users/jason/NodeProjects/ViteFastify/simple/node_modules/fastify-vite-vue/routing.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.<anonymous> (/Users/jason/NodeProjects/ViteFastify/simple/node_modules/vite/dist/node/chunks/dep-76613303.js:60126:20)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (/Users/jason/NodeProjects/ViteFastify/simple/node_modules/fastify-vite-vue/app.js:12:5)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/Users/jason/NodeProjects/ViteFastify/simple/node_modules/fastify-vite-vue/app.js',
    '/Users/jason/NodeProjects/ViteFastify/simple/node_modules/fastify-vite-vue/routing.js'
  ]
}

Expected Behavior

It to build and run correctly.

Quickstart of React example failed in start script

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

3.29.0

Plugin version

No response

Node.js version

16.x

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

11.6.2

Description

I tried to use the QuickStart example with React, I've followed the steps as per the docs:

  1. create a folder
  2. install all dependencies
  3. create a app.mjs file according with the snippet
  4. create a index.jsx file in views folder

When I run the command "node app.mjs" I have the following response:

❯ node app.mjs                                                        
file:///Users/lucasbittencurt/www/ssr-vite/app.mjs:9
await app.vite.commands()
               ^

TypeError: app.vite.commands is not a function
    at file:///Users/lucasbittencurt/www/ssr-vite/app.mjs:9:16
    at processTicksAndRejections (node:internal/process/task_queues:96:5)```

### Steps to Reproduce

Follow the quickstart for React with node version 16.x 

### Expected Behavior

Expected to run a Fastify server correctly.

Error on basic install from docs

This is my first experience with fastify-vite and I'm attempting to follow the Vue quickstart instructions, however I get the following error when running node app.mjs

  • C:\Users\Jeff\fite\node_modules\vite\dist\node\chunks\dep-85dbaaa7.js:66477
    throw new Error(failed to load module for ssr: ${url});

[Bug] 2.3.0 not building

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

3.23.1

Plugin version

2.3.0

Node.js version

14.7 + 15.x

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

tried on mac, linux (both github actions and circleci)

Description

Running node index.ms build is running the server and doesn't generate the dist directory.

Steps to Reproduce

  1. use 2.2.4 - run node index.ms build - will work.
  2. re-install the plugin at version 2.3.0 - fastify server will run, dist folder will not be created

Expected Behavior

dist folder should be created with relevant files, and the process should be exited with code 0.

Dynamic component import at server doesn't include CSS

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

3.25.3

Plugin version

"fastify-vite-vue": "^3.0.0-alpha.12"

Node.js version

14.7

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

12.1 (21C52)

Description

I use a dynamic lazy load of components as part of the layout, like that:

return import(`../components/layouts/${componentName}.vue`).then(component => {
      components[componentName] = component.default;
    })

Those components are loaded in both SSR and frontend, but its CSS doesn't include in the SSR resource.

Steps to Reproduce

  1. load component dynamically using the import() function.
  2. use this component.
  3. see that it renders.
  4. add some CSS inside the component (border / color / background).
  5. disable javascript in the browser.
  6. see that it only loads the CSS after hydration when JS is enabled.

Expected Behavior

CSS should be included in the SSR bundle, with hydration.

How to inline CSS to control Content Layout Shift metric

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

Hi There.

I use Google PageSpeed Insights tool time to time for monitoring our website metrics.
It has the Content Layout Shift (CLS) metrics which is poor by default to me.

I'd like to know is any way how to pass minimum critical css styles from Vue components to main layout (client.vue) or even to index.hml to avoid CLS issues ?

As a workaround, right now I have to do the following things:

  1. To define manually minimum critical css in client.vue, or any other Page Vue components
const minCriticalCss = {
  style: [{
    type: 'text/css',
    children: '<important content>'
  }]
};
  1. To pass minCriticalCss to useHead call.

But, it is obviously akward to maintain. What alternativies can you recommend ?

Vue Minimal Boilerplate example error

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

3.26.0

Plugin version

2.3.1

Node.js version

14.18.3

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

12.0.1

Description

I tried to follow the example here and am getting the following error

TypeError: __vite_ssr_import_1__.createMemoryHistory is not a function
    at createApp (@app/client.js:13:25)
    at async render (/Users/elliottross/projects/pulse/node_modules/.pnpm/[email protected]/node_modules/fastify-vite-vue/render.js:11:48)
    at async Object.<anonymous> (/Users/elliottross/projects/pulse/node_modules/.pnpm/[email protected]/node_modules/fastify-vite-vue/handler.js:21:25)

Steps to Reproduce

  1. Create app.mjs with what is in the minimal boilerplate example
  2. Create views/index.vue with what is in the minimal boilerplate example
  3. Run node app.mjs

Expected Behavior

No error to show and page to render

Documentation doesn't cover version 3.x yet it's the default installed version

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

3.25.0

Plugin version

3.0.0-alpha.2

Node.js version

14.x

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

Linux Mint 20.2 (Uma)

Description

First, I'm grateful for the great work done here, I really appreciate it as I was looking for exactly this for my project.

Ok, so my problem(s) are:

  • Installing this plugin currently installs the alpha version which is 3.x, but both the documentation and GitHub only show details for version 2.x.
  • Documentation doesn't seem up-to date, my point being, I had to go to the issues to find out that i needed app.vite.commands() in order to run eject(so am not sure to use both ready() and commands(),or just one of them), which was also another roller coaster ride to get to that point. From the issue is where I saw a reply saying to check the breaking changes, which I could only find in the GitHub release page, which, at the same time, doesn't even show the version I have installed.
  • Adding custom CSS, was hectic too, and even as I got it working now, I'm not sure if it's the right way.

So, to sum it up, I guess I'm saying I need help. Example below, is one of the problems I came upon.
I spent so much time with this since I really like the project, but it had me confused all over. Please help..

Steps to Reproduce

I setup as directed in the docs.

My server.js:

const { PORT, PINO_CONFIG } = require("./utils");
const fastify = require("fastify")({ logger: PINO_CONFIG });
const FastifyVite = require("fastify-vite");
const renderer = require("fastify-vite-vue");
const path = require("path");

const dev = process.env.NODE_ENV === "development";

const main = async () => {
  await fastify.register(FastifyVite, {
    api: true,
    root: __dirname,
    renderer,
    vite: {
      build: {
        outDir: path.resolve(__dirname, "api"),
        minify: !dev,
      },
    },
  });
  await fastify.decorate("app_root", path.resolve(__dirname));
  await fastify.register(require("./core/plugins")); // Other Fastify plugins I wanna use
  await fastify.register(require("./core")); // My routes
  await fastify.vite.commands();
  await fastify.vite.ready();
  return fastify;
};

if (require.main === module) {
  main().then(fastify => {
    fastify.listen(PORT, err => {
      if (err) {
        fastify.log.error(err);
        process.exit(1);
      }
      console.log(fastify.app_root, fastify.config);
    });
  });
}

module.exports = main;

In my views/index.vue:

<script>
import { onMounted } from "vue";
import { useHydration } from "fastify-vite-vue/client.mjs";

export const path = "/api";
export default {
  name: "Index",
  async setup() {
    const ctx = await useHydration();
    onMounted(() => {
      console.log(ctx);
    });
    return { ctx };
  },
};
</script>

<template>
  <h1>Hello World {{ $global }} - {{ ctx }}</h1>
</template>

This in turn throws the error below:
[vite] Error when evaluating SSR module @app/routes.js: Error: Failed to resolve import "fastify-vite-vue/client.mjs" from "views/index.vue". Does the file exist?

Upon checking, I couldn't find the client.mjs file and even the useHydration hook.

The $global variable is empty, which I'm assuming is not an error, it just means it's not populated yet.

Expected Behavior

No response

isServer doesn't work as import.meta.env.SSR

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

3.23.1

Plugin version

2.3.0

Node.js version

14.7

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

11.6

Description

my app is using vue-ts

SSR code should be tree-shaked from client dist

Steps to Reproduce

write something like:

if(import.meta.env.SSR) {
  // code that will tree-shaked from client dist.
}

when doing:

import {isServer} from 'fastify-vite-vue/client.mjs';

if(isServer) {
  // code that will NOT tree-shaked from client dist.
}

Expected Behavior

SSR code should be tree-shaked from client dist

Route definition duplicate error

Hi, thank you for the updates. You made an amazing work!

I have a question about correct route definitions.
In my case, I'd like to execute some code before page rendering, so I defined:

a route in server.js with preHandler hook

fastify.route({
        method: 'GET',
        url: '/',
        preHandler: logMetricsStatic('homepage', 'GET'),
        handler: fastify.vite.handler
    });

and then in routes.js

{
        path: '/',
        component: MainLayout,
        children: [
            {
                path: '',
                component: Index,
            },
        ],
    },

After upgrade fastify-vite from 2.2.0-beta.2 to 2.2.0-beta.13 I started getting error message

Method 'GET' already declared for route '/' with constraints '{}'

Could you please give me an advice, how to make a proper route definition with hooks ?

SPA mode results in `Cannot read properties of null`

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.9.2

Plugin version

3.0.0-beta.27

Node.js version

16.18.0

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

12.6

Description

When I enable SPA:

await server.register(FastifyVite, {
  dev: process.argv.includes("--dev"),
  root: import.meta.url,
  spa: true,
});

I'm getting

TypeError: Cannot read properties of null (reading 'routes')
    at Vite.setup (/xxx/node_modules/fastify-vite/mode/development.js:57:35)
    at async Vite.ready (/xxx/node_modules/fastify-vite/index.js:32:55)
    at async file:///xxx/server.js:17:1

Also seems kind of obvious to me that this will always fail looking at development.js:

const loadClient = async () => {
    if (config.spa) {
      return null
    }
...
sync prepareClient (clientModule, scope, config) {
    if (!clientModule) {
      return null
    }
...
return { client, routes: client.routes, handler, errorHandler }

Steps to Reproduce

Enable SPA:

await server.register(FastifyVite, {
  dev: process.argv.includes("--dev"),
  root: import.meta.url,
  spa: true,
});

Expected Behavior

Either enabling SPA should work or there should be a clear instruction on how to set it up.
Would be nice to have a SPA example (preferable in Svelte).

npm ERR! ERESOLVE unable to resolve dependency tree when doing npm install under examples/svelte-hydration

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

3.29.1

Plugin version

3.0.0-beta.24

Node.js version

18.6.0

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

12.4

Description

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: undefined@undefined
npm ERR! Found: [email protected]
npm ERR! node_modules/vite
npm ERR! dev vite@"^2.9.9" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer vite@"^3.0.0" from @sveltejs/[email protected]
npm ERR! node_modules/@sveltejs/vite-plugin-svelte
npm ERR! dev @sveltejs/vite-plugin-svelte@"^1.0.0-next.44" from the root project
npm ERR!

Steps to Reproduce

Go to examples//svelte-hydration then npm i.

Expected Behavior

npm i should succeed installing dependencies.

Improve handling of Vite configuration

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

🚀 Feature Proposal

Standardize on config.js as the configuration file automatically loaded for fastify-vite applications, both for brevity and clear distinction from vite.config.js. Nest Vite options under a vite option from the main export.

Motivation

  1. Ensuring Vite config loading goes through the Fastify plugin allows for dynamic changes.

  2. Naming it differently than vite.config.js prevents clashes and unwanted behavior if the user is unaware of fastify-vite being used in a project and tries to run commands through Vite's CLI.

Example

No response

Have you seen vite-plugin-node can you do something similar for HMR?

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

The main reason I would like to use vite is HMR which your plugin does not do. I like the fact you are trying to keep thing simple which using vite and vite-plugin-node does not do.
That also the reason i like yarn3 IMHO it look simpler then npm but sadly a lot of programs crashes with it.

  • what the difference between vite-plugin-node and yours beside running on fastify and not be able to HMR
  • is there a reason you are make a plugin for fastify?
  • would a rewrite be justifiable?
  • I see this is part of fastify so can't you fix this limitation you motion in the FAQ?

The reason I am asking ,I been trying to use your plugin but everything keep crashing and wounding if I should come back later

first with missing dependencies
I had to add a lot those from dependencies.md and then i had to run
npm install vue-router@4

And it still crashes with

[Vue warn]: inject() can only be used inside setup() or functional components.
[Vue warn]: Server rendering context not provided. Make sure to only call useSSRContext() conditionally in the server build.
[Vue warn]: Unhandled error during execution of setup function
at
TypeError: Cannot read properties of undefined (reading 'modules')
at _sfc_main.setup (@app/client.vue:66:16)
at callWithErrorHandling (/home/pi/system-admin/node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:6582:22)
at setupStatefulComponent (/home/pi/system-admin/node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:6208:29)
at setupComponent (/home/pi/system-admin/node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:6164:11)
at renderComponentVNode (/home/pi/system-admin/node_modules/fastify-vite-vue/node_modules/@vue/server-renderer/dist/server-renderer.cjs.js:198:17)
at /home/pi/system-admin/node_modules/fastify-vite-vue/node_modules/@vue/server-renderer/dist/server-renderer.cjs.js:456:30
at Generator.next ()
at /home/pi/system-admin/node_modules/fastify-vite-vue/node_modules/@vue/server-renderer/dist/server-renderer.cjs.js:30:71
at new Promise ()
at __awaiter (/home/pi/system-admin/node_modules/fastify-vite-vue/node_modules/@vue/server-renderer/dist/server-renderer.cjs.js:26:12)
{"level":30,"time":1644762988964,"pid":17513,"hostname":"frog64debain","reqId":"req-1","res":{"statusCode":500},"responseTime":254.15144681930542,"msg":"request completed"}

I thought it might be the fact i trying to use yarn( i tried all kind of version) then i tried to use npm still have this error

running on my raspberry pi with latest version of node. Vite run fine

  • I thought you might have not seen vite-plugin-node and it might be helpful in your endeavor

SPA Documentation / Examples

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

Hi there 👋

I'm working on setting up fastify-vite in SPA mode, and I would like to use this plugin to serve my static build.

There are some comments in the README that suggest there is an SPA example, but it doesn't appear to exist. I'd be happy to contribute a PR with an example, but I'm a bit unsure on some of the requirements

When using fastify-vite to serve a built application, does a user always need to provide a server entrypoint as well? Looking at this example, the comment suggests that its required for SSR but I'm not sure about how SPAs fit in to the picture.

Thanks for your time and work on this plugin!

Supporting routes with layout and different props was broken

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the regression has not already been reported

Last working version

2.2.0-beta.2

Stopped working in version

2.2.3

Node.js version

14.18.1

Operating system

Windows

Operating system version (i.e. 20.04, 11.3, 10)

Windows 10

💥 Regression Report

Hi There.

My test example is placed here (https://github.com/SuslegStyle/fastify-vite-hello-world)
Let me describe my use case.

I have a custom routes.js file where I define routes like

export default () => [
    {
        path: '/',
        component: Layout,
        props: {testProperty: 'Hello world'},
        children: [
            {
                path: '',
                component: Index,

            }
        ]
    },
    {
        path: '/',
        component: Layout,
        props: {testProperty: 'Hello external world'},
        children: [
            {
                path: 'external/',
                component: Index //TODO: in real app it is another page component
            }
        ]
    }
];

I use props to pass correct value to layout. In the real app, the props value changes Header.
After upgrading to 2.2.3 I start getting error during the build
Method 'GET' already declared for route '/' with constraints '{}'

Steps to Reproduce

First issue

  1. Clone my example
  2. Run npm run build
internal/process/promises.js:213
        triggerUncaughtException(err, true /* fromPromise */);
        ^

AssertionError [ERR_ASSERTION]: Method 'GET' already declared for route '/' with constraints '{}'
    at Router._insert (D:\fastify-vite-hello-world\node_modules\find-my-way\index.js:303:7)
    at Router._on (D:\fastify-vite-hello-world\node_modules\find-my-way\index.js:231:8)
    at Router.on (D:\fastify-vite-hello-world\node_modules\find-my-way\index.js:100:8)
    at Object.afterRouteAdded (D:\fastify-vite-hello-world\node_modules\fastify\lib\route.js:254:16)
    at D:\fastify-vite-hello-world\node_modules\fastify\lib\route.js:181:25
    at Object._encapsulateThreeParam (D:\fastify-vite-hello-world\node_modules\avvio\boot.js:551:7)
    at Boot.timeoutCall (D:\fastify-vite-hello-world\node_modules\avvio\boot.js:447:5)
    at Boot.callWithCbOrNextTick (D:\fastify-vite-hello-world\node_modules\avvio\boot.js:428:19)
    at Boot._after (D:\fastify-vite-hello-world\node_modules\avvio\boot.js:273:26)
    at Plugin.exec (D:\fastify-vite-hello-world\node_modules\avvio\plugin.js:132:19) {
  generatedMessage: false,
  code: 'ERR_ASSERTION',
  actual: false,
  expected: true,
  operator: '=='
}

Second issue

There is a second issue, that start reproducing again.
If in my routes.js change line 18 to path: '/my', then we get the error

D:\fastify-vite-hello-world\node_modules\fastify-vite\build.js:25
  const outDir = vite.build.outDir || 'dist'
                      ^

TypeError: Cannot read property 'build' of null
    at build (D:\fastify-vite-hello-world\node_modules\fastify-vite\build.js:25:23)
    at Object.fastify.vite.ready (D:\fastify-vite-hello-world\node_modules\fastify-vite\index.js:208:13)
    at processTicksAndRejections (internal/process/task_queues.js:95:5)
    at async main (D:\fastify-vite-hello-world\server.js:30:5)

Third issue

I tried to change fastify-vite/build.js file at line 25
from const outDir = vite.build.outDir || 'dist'
to const outDir = vite?.build?.outDir || 'dist'

Then the application is built successfully, but I got the runtime error that appContext is null. (We already faced the issue before)

TypeError: Cannot read property 'appContext' of null
    at useGlobalProperties (/node_modules/fastify-vite-vue/client.mjs?v=e94165ef:133:30)
    at Module.useHydration (/node_modules/fastify-vite-vue/client.mjs?v=e94165ef:20:23)
    at setup (d:/fastify-vite-hello-world/pages/index.vue:8:24)
    at _sfc_main.setup (/pages/index.vue:48:23)
    at callWithErrorHandling (D:\fastify-vite-hello-world\node_modules\vue\node_modules\@vue\runtime-core\dist\runtime-core.cjs.js:6620:22)
    at setupStatefulComponent (D:\fastify-vite-hello-world\node_modules\vue\node_modules\@vue\runtime-core\dist\runtime-core.cjs.js:6246:29)
    at setupComponent (D:\fastify-vite-hello-world\node_modules\vue\node_modules\@vue\runtime-core\dist\runtime-core.cjs.js:6202:11)
    at renderComponentVNode (D:\fastify-vite-hello-world\node_modules\vue\node_modules\@vue\server-renderer\dist\server-renderer.cjs.js:198:17)
    at renderVNode (D:\fastify-vite-hello-world\node_modules\vue\node_modules\@vue\server-renderer\dist\server-renderer.cjs.js:304:22)
    at renderVNode (D:\fastify-vite-hello-world\node_modules\vue\node_modules\@vue\server-renderer\dist\server-renderer.cjs.js:310:17)

Expected Behavior

The application should be successfully built and works properly.

Generating preload directives or changing bundle included in rendered HTML

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

🚀 Feature Proposal

Let's say we have an example app with the following routes:

/ -> HomePage
/about -> AboutPage

And assume in the project, I've implemented code splitting (using await import) - to make sure AboutPage and HomePage bundles are separate.

  • When I land on "localhost:3000/" - the generated HTML should only contain the bundle for HomePage - and preload directives for the HomePage
  • Likewise, when I land on "localhost:3000/about" the generated HTML should only contain the bundle for AboutPage - and preload directives for the HomePage

And finally, along the same lines:

  • To implement "preload on hover" i.e. preload the bundle when user hovers on the link to another page

Motivation

Being able to only load the bundles required for the page being rendered.

I can currently see config values exposed for customising the template, but nothing for customising the bundle that gets added to the HTML.

Things I am unable to see a clear picture (as a Vite newbie):

  • How we can use the ssr-manifest to find the bundles used in the current render path (i.e. how do we know the moduleIds, especially when rendering React?)
  • How Vite or Fastify-Vite is inserting the bundle in the first place

Example

There is an example on the Vite SSR docs: https://vitejs.dev/guide/ssr.html#generating-preload-directives (with some broken links) - where they suggest that the vite-vue plugin contains support for collecting moduleIds on render - no equivalent for React.

Cannot override `clientModule` location

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

3.29.0

Plugin version

3.0.0-beta.21

Node.js version

v16.13.1

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

12.3.1

Description

I would like to override the default path of clientModule - the first problem is that the documentation is a little difficult to understand - especially with no TypeScript. Perhaps it would be better to have an example showing where the config object is passed (i.e. its hard to tell whether we configure the vite plugin, or the fastify plugin).

import {createRoute, createErrorHandler} from './fastifyViteConfig.mjs'

await server.register(FastifyVite, {
  root,
  renderer: {
	clientModule: '/path/to/your/server/entry.js' // 👈  here? *(1)
	createRoute,
        createErrorHandler
        // ....
  },
  clientModule: '/path/to/your/server/entry.js' // 👈  or here? *(2)
});

And second, even when I supply clientModule, it seems to error out:

  • If I supply a path, it errors out with:

when passing it inside the render object (1):

   throw new Error(`failed to load module for ssr: ${url}`);

and when passed outside (2):

    const modulePath = resolve(config.vite.root, config.clientModule.replace(/^\/+/, ''))
                                                                     ^

TypeError: Cannot read properties of null (reading 'replace')

It doesn't matter whether this path is correct or not

  • If I supply an object
    There seems to be issues loading the createApp function

Steps to Reproduce

  1. Rename client/index.js to client/clientModule.js in the React hydration example
  2. Supply the clientModule in server.js
await server.register(FastifyVite, {
  root,
  renderer,
+  clientModule: 'client/clientModule.js',
});
  1. Run yarn dev

Expected Behavior

  • The path to my client module should be used
  • Documentation needs an update (happy to PR once I get a bit of direction)

Missing monorepo scripts

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

Hi!
While trying to contribute to the project, I've noticed that it uses the packages folder as specified in the workspaces docs (https://docs.npmjs.com/cli/v7/using-npm/workspaces), but some links in the main package.json are missing:

{
  ...
  "workspaces": [
    "fastify-vite",
    "fastify-vite-react",
    "fastify-vite-vue"
  ],
  ...
}

that would help enforce dependency versions consistency amongst different packages and also enables a series of helpful npm scripts to manage the monorepo.

Is there a specific reason why the project is not set up as an npm monorepo? If not, I'd be glad to help with the setup!

Vanilla Example?

Hello, Very nice work, thanks for it.

Nice that in the Examples folder there are examples for react & vue is it possible to get a super minimal example to have exactly what these two examples do but without framework at all just for better understanding?

Thanks

Blueprints video link is broken in README.md

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

Hi !
Thanks for what you are building.

When reading the documentation, I tried clicking on the blueprint link, I landed on this page :
image

Suggestion: run payload and data functions directly instead of using Function.call()

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

I saw this area when creating the routes on fastify:

        preHandler.push(
          async function (req, reply) {
            req[options.hydration.data] = await getData.call(
              this,
              {
                req,
                params: req.params,
                reply,
                $api: this.api && this.api.client,
                fastify: this,
                fetch,
              },
            )
          },

From my little knowledge, the "this" of the payload and data functions are useless, and also injected as "fastify", so we can skip this binding just by doing:

        preHandler.push(
          async function (req, reply) {
            req[options.hydration.data] = await getData(
              {
                req,
                params: req.params,
                reply,
                $api: this.api && this.api.client,
                fastify: this,
                fetch,
              },
            )
          },

probably will be more efficient this way.
what do you think?

UseServerApi, UseServerData not working with fastify-api nested objects

Hi There,

I use fastify-api package, so, I use UseServerApi, UseServerData hooks for gathering initial data.
Just like in the example app.
I defined a route

({ get }) => ({
  pages: {
      homepage: get('/api/pages/homepage', async (req, reply) => {
            const sdk = fastify.diContainer.resolve('sdk');
            const data = await sdk.getData();
            reply.send({ data });
      })
  }

Then, I fetch the data

const data = await useServerData(async () => {
  const { json } = await api.pages.homepage();
  return json;
})

It works fine at first.
Then, I change to hello page and back to index page using navigation links.

And I get error

    at Object.getFetchWrapper [as get] (vendor.06caa955.js:8232)
    at index.bc61efbc.js:130
    at Object.useServerData (hooks.be7e0b88.js:32)
    at setup (index.bc61efbc.js:129)
    at callWithErrorHandling (vendor.06caa955.js:1026)
    at setupStatefulComponent (vendor.06caa955.js:5017)
    at setupComponent (vendor.06caa955.js:5004)
    at mountComponent (vendor.06caa955.js:3578)
    at processComponent (vendor.06caa955.js:3567)
    at patch (vendor.06caa955.js:3325)

If I change route definition to avoid using nested methods, simply await api.homepage() then it start working.

Vite is not defined

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

3.27.1

Plugin version

2.3.1

Node.js version

16.13.2

Operating system

Windows

Operating system version (i.e. 20.04, 11.3, 10)

11

Description

I'm working for SSR in Fastify with Vue3 in TS, but when i run the start server file, it will come a error with "vite is not defined" and i don't know why..
This is an repo example that I'm following a little bit: https://github.com/Rezvitsky/vitejs-ssr

I don't really know where the error originates, so I just want to ask here..

Thank you for your help

Steps to Reproduce

https://github.com/Rezvitsky/vitejs-ssr

Expected Behavior

No response

fastify-vite_hydrate.js does not provide an export named 'hydrate'

Hi guys,

I tried to use fastify-vite on my application based on your example app.
I face the issue when run npm run build and npm run dev commands.
In browser console I see error

Uncaught SyntaxError: The requested module '/node_modules/.vite/fastify-vite_hydrate.js?v=8f84e2b7' does not provide an export named 'hydrate'

But my entry/client.js file is the following

`
import { createApp } from '../main';
import { hydrate } from 'fastify-vite/hydrate';
const { app, router } = createApp();

hydrate(app);

// Wait until router is ready before mounting to ensure hydration match
router.isReady().then(() => app.mount('#app'));
`

Looks like something goes wrong under the hood.

If I run npm run build and npm run serve then I don't see the issue, but I can't debug the application.

vite.config.js

Good day sir,
Thank you for the amazing work!

I am trying out 2 things

first is changing root directory
I would want something like

everythingElse
-- dist
-- entry
-- pages
etc...

node_modules
vite.config.js
package.json

this is my vite.config.js

import viteCompression from 'vite-plugin-compression';

export default: {
        root: 'everythingElse'
        plugins: [viteCompression()],
};

second is to be able to generate gz and br files and serve them instead of an on the fly compression.

It seems like it is not working. Or i might be wrong in my vite.config.js
Is this how it should look like?
Proxy on the otherhand works fine.

This is my first time using vite and fastify.
Any help is deeply appreciated.

Thank you

SolidJS support

Creating this issue thread as a proposal for adding SolidJS support. I'll probably make a PR for this, otherwise others can probably make this as well.

If I were to write the renderer plugin, where should I begin?

Edit:
I just checked the React renderer and it seems that the renderer was written in JS (not TS) and in CommonJS format. I'll probably just make a third-party renderer

TypeScript support

This project is amazing. Would be great to have an example using typescript at both side: server and Vue 3

fastify-vite-vue:useServerAPI Cannot read property 'appContext' of null

He guys. Could you please help me?

Today I faced the issue

TypeError: Cannot read property 'appContext' of null
    at Proxy.useServerAPI (***\node_modules\fastify-vite-vue\client.js:47:41)

Looks like the internal method getCurrentInstance() returns null.

As a workaround I have to use try catch for useServerAPI method, but my page does not get data from SSR.

Just in case, list of my project's dependencies

"dependencies": {
    "@mgcrea/fastify-session": "^0.14.1",
    "@mgcrea/fastify-session-redis-store": "^0.9.1",
    "@popperjs/core": "^2.9.2",
    "@vueuse/head": "^0.6.0",
    "async": "^3.2.0",
    "awilix": "^4.3.4",
    "bootstrap-icons": "^1.5.0",
    "fastify": "^3.18.0",
    "fastify-api": "^0.2.0",
    "fastify-awilix": "^1.1.0",
    "fastify-config-loader": "^1.1.2",
    "fastify-cookie": "^5.3.1",
    "fastify-plugin": "^3.0.0",
    "fastify-sensible": "^3.1.1",
    "fastify-static": "^4.2.2",
    "fastify-vite": "^2.2.0-beta.2",
    "fastify-vite-vue": "^2.2.0-beta.2",
    "ioredis": "^4.27.6",
    "ipaddr.js": "^2.0.1",
    "vite": "^2.3.8",
    "vue": "^3.1.2",
    "vue-router": "^4.0.10"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^1.2.3",
    "@vue/compiler-sfc": "^3.1.2",
    "bootstrap": "^5.0.2",
    "cross-env": "^7.0.3",
    "eslint": "^7.29.0",
    "eslint-plugin-import": "^2.23.4",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-vue": "^7.11.1",
    "sass": "^1.35.1"
  }

Quickstart steps lead to infinite reload loop if HTTPS enabled

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

3.28.0

Plugin version

2.3.1

Node.js version

17.6.0

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

21.4.0

Description

Following steps at: https://fastify-vite.dev/quickstart/vue.html result in an infinite reload loop. No idea why.

Steps to Reproduce

  1. Install deps:
npm i fastify fastify-vite fastify-vite-vue --save
  1. app.js
import Fastify from 'fastify'
import FastifyVite from 'fastify-vite'
import renderer from 'fastify-vite-vue'

import {readFileSync} from 'node:fs'
const https = {
  cert: readFileSync('tier-dev-tailscale.pem'),
  key: readFileSync('tier-dev-tailscale-key.pem'),
}

const root = import.meta.url
const app = Fastify({
  logger: true,
  https,
})

await app.register(FastifyVite, { root, renderer })
await app.vite.commands()
await app.listen(+process.env.PORT || 443, '0.0.0.0')
  1. views/index.vue
<template>
  <h1>Hello World</h1>
</template>

<script>
export const path = '/'
</script>
  1. package.json file:
{
  "name": "@tier.run/tierweb",
  "version": "0.0.0",
  "type": "module",
  "main": "app.js",
  "dependencies": {
    "fastify": "^3.28.0",
    "fastify-vite": "^2.3.1",
    "fastify-vite-vue": "^2.3.1",
    "pino-pretty": "^7.6.0"
  }
}
  1. Run node app.js
  2. Open page in browser, results in infinite flashing re-load.

Resulting logs: https://gist.github.com/b3934ff57a86a5cb6b51616ddce2b4c3

Expected Behavior

Should load content once, not infinitely many times as fast as possible.

upgrade to fastify 4

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

hi,
first thanks for this good idea of bringing fastify and vite together!
I'm wondering if there is any reason to use fastify 3 instead of fastify 4? I'm just starting a new project with fastify-vite and it seems easier for me to migrate now than later ;)

please tell me if you need any help for this migration! I'm definetly not a fastify expert, but I can try to help.

cannot find index.ts in production

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

3.29.0

Plugin version

3.0.0-beta.23

Node.js version

16.15.0

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

archlinux

Description

hi,

I'm using fastify-vite with typescript, and after building for production (with command vite build --outDir dist/server --ssr /index.ts) I get the following error:

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/home/me/mon-app/client/dist/server/index.ts' imported from /home/me/mon-app/node_modules/.pnpm/[email protected]/node_modules/fastify-vite/mode/production.js

To fix it I made a quick and dirty fix in mode/production.js

@@ -49,7 +49,7 @@
 
   // Loads the Vite application server entry point for the client
   async function loadClient () {
-    const serverFile = join('server', basename(config.clientModule))
+    const serverFile = join('server', basename(config.clientModule).replace('.ts', '.js'))
     const serverBundle = await import(resolve(config.bundle.dir, serverFile))
     return serverBundle.default ?? serverBundle
   }

maybe I miss some configuration step.

Steps to Reproduce

to reproduce use any example and rename client/index.js to client/index.ts then run

vite build --outDir dist/server --ssr /index.ts

Expected Behavior

No response

getPayload should be tree-shaked from client dist

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

🚀 Feature Proposal

Inside my component file, when I export the getPayload function, it should be tree-shaked from the client code dist files.

Also, to tree-shake everything that is only used by the getPayload functions (such as backend libraries).

Motivation

to reduce the bundle size and to remove, and not expose code that runs on the backend.

Example

I managed to create a workaround that actually works in here:
https://github.com/greenpress/greenpress/blob/dynamic-front-ssr/apps/front-ssr/views/index.vue

Note: it's not tree-shaking the sdk import that is only used by the getPayload.

As you can see, I wrapped the original getPayload with a conditional import.meta.env.SSR.
I also passed true as a value to the useHydration hook in order to make it call the payload even though I don't have the original function.

Move renderer dependencies to peerDependencies

You have specified vue version in package.json without giving an ability to change it. Please move the vue dependency to peerDependencies.

This is applied to: @vue/compiler-sfc, @vue/server-renderer, vue, vue-router.

Please move there @vitejs/plugin-vue and @vitejs/plugin-vue-jsx too.

At the moment I'm using workaround via yarn resolutions.

  "resolutions": {
    "vue": "^3.2.12",
    "@vue/compiler-sfc": "^3.2.12",
    "@vue/server-renderer": "^3.2.12",
    "vite": "^2.5.10",
    "vue-router": "^4.0.11",
    "@vitejs/plugin-vue": "1.8.1",
    "@vitejs/plugin-vue-jsx": "1.1.8"
  }

Route management

is there any option/api for managment routes?

How deal with it.
Routs basicually need baseURL, named route for generate url base on parameters and etc.

Thanks for your awesome project bwt

Support <script setup>

Hi,
I may wrong, but

<script setup>
export const path = '/about'
</script>

does not seem to be working. Is there a way to make it work? <script setup> is recommended way to use components since version 3.2. Something like

<script setup>
import { definePath } from 'fastify-vite'

definePath('/about')
</script>

But I don't know if this would be suitable for other exported variables.

Pug support

Would you be interested to support Pug or how i do?

I see in Vite Pug works fine, but not with fastify-vite.

Registering a post route

I am trying to have a better understanding of server.js and Fastify in general.. I'm sure I am missing something obvious, but I can't seem to get this to work. And often receive the error message.

AssertionError [ERR_ASSERTION]: The first character of a path should be /or*``

Furthermore, lets say in nuxt I used fetch() to do

await fetch(
      'https://us-east-1.aws.realm.mongodb.com/api/client/v2.0/app/dream-hfcur/graphql',
      requestOptions
    )
      .then((response) => response.json())
      .then((data) =>
        data.data.images.forEach((x) =>
          this.imgData.push({
            url: x.url.replace('.tiff', '.jpeg'),
            title: x.title,
          })
        )
      )

Request options being:

const requestOptions = {
  method: 'POST',
  headers: {
    'Access-Control-Allow-Origin': '*',
    'Content-Type': 'application/json',
    apiKey: 'ApiKey'
  },
  body: JSON.stringify({
    query: 'query { images(sortBy: _ID_DESC) { _id title url }}'
  })
}
  1. I should do the data formatting in the reply({}), yes?

  2. I had to add a proxy to nuxt.config.js for my graphql route because of CORS issues, will I have to do the same?

I've added the following code to server.js

const requestOptions = {
  method: 'POST',
  headers: {
    'Access-Control-Allow-Origin': '*',
    'Content-Type': 'application/json',
    apiKey: 'ApiKey'
  },
  body: JSON.stringify({
    query: 'query { images(sortBy: _ID_DESC) { _id title url }}'
  })
}
const requestOptions = {
  method: 'POST',
  headers: {
    'Access-Control-Allow-Origin': '*',
    'Content-Type': 'application/json',
    apiKey: 'ApiKey'
  },
  body: JSON.stringify({
    query: 'query { images(sortBy: _ID_DESC) { _id title url }}'
  })
}

fastify.post('/*', fastify.vite.handler)

  1. What do I need to add to server.js to have this working let fetch?

BTW this is so cool. I was so interested in Fastly, so to have this pushed me over the edge to dive deep.

Compile server dist file to mjs instead of cjs

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

🚀 Feature Proposal

compile the server app into mjs file instead of cjs.

Motivation

mjs has top-level await like the browser also has, and it's much more consistent.

Example

When I ran the app on dev mode, I managed to write a line like await import("my-third-party-dep") on a file's top-level, but this line failed to compile (the build failed).

When I tried to use something like:

// this all area is removed from the client dist anyway:
if(import.meta.env.SSR) {
  require("my-third-party-dep")  
}

It didn't run for both dev and build, with the error:
ReferenceError: require is not defined

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.