fastify / fastify-vite Goto Github PK
View Code? Open in Web Editor NEWFastify plugin for Vite integration.
License: MIT License
Fastify plugin for Vite integration.
License: MIT License
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?
3.28.0
2.3.1
17.6.0
macOS
21.4.0
Following steps at: https://fastify-vite.dev/quickstart/vue.html result in an infinite reload loop. No idea why.
npm i fastify fastify-vite fastify-vite-vue --save
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')
<template>
<h1>Hello World</h1>
</template>
<script>
export const path = '/'
</script>
{
"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"
}
}
node app.js
Resulting logs: https://gist.github.com/b3934ff57a86a5cb6b51616ddce2b4c3
Should load content once, not infinitely many times as fast as possible.
3.29.0
3.0.0-beta.23
16.15.0
Linux
archlinux
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.
to reproduce use any example and rename client/index.js to client/index.ts then run
vite build --outDir dist/server --ssr /index.ts
No response
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 ?
Are there plans for server HMR?
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.
yarn dev would hmr on client and server
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
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
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
3.25.3
"fastify-vite-vue": "^3.0.0-alpha.12"
14.7
macOS
12.1 (21C52)
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.
import()
function.CSS should be included in the SSR bundle, with hydration.
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.
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.
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.
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
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.fastify-vite-vue
, there must be two separate renderers, so that in production mode vite.ssrLoadModule
is excluded by tree shaking.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.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.
3.23.1
2.3.0
14.7
macOS
11.6
my app is using vue-ts
SSR code should be tree-shaked from client dist
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.
}
SSR code should be tree-shaked from client dist
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"
}
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.
This is a great addition to the Fastify ecosystem. Would you be interested to support React in addition to Vue?
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!
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.
3.29.0
3.0.0-beta.21
v16.13.1
macOS
12.3.1
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:
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
createApp
functionclient/index.js
to client/clientModule.js
in the React hydration exampleawait server.register(FastifyVite, {
root,
renderer,
+ clientModule: 'client/clientModule.js',
});
yarn dev
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"
}
3.29.0
No response
16.x
macOS
11.6.2
I tried to use the QuickStart example with React, I've followed the steps as per the docs:
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.
2.2.0-beta.2
2.2.3
14.18.1
Windows
Windows 10
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 '{}'
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: '=='
}
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)
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)
The application should be successfully built and works properly.
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
This project is amazing. Would be great to have an example using typescript at both side: server and Vue 3
3.29.1
3.0.0-beta.24
18.6.0
macOS
12.4
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!
Go to examples//svelte-hydration
then npm i
.
npm i
should succeed installing dependencies.
4.2.1
3.0.0-beta.23
16.x
Windows
10
unocss not work when add class in page element.
<h1 class="text-hex-333">{{ message }}</h1>
No response
4.9.2
3.0.0-beta.27
16.18.0
macOS
12.6
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 }
Enable SPA:
await server.register(FastifyVite, {
dev: process.argv.includes("--dev"),
root: import.meta.url,
spa: true,
});
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).
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.
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
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!
3.23.1
2.3.0
14.7 + 15.x
Linux
tried on mac, linux (both github actions and circleci)
Running node index.ms build
is running the server and doesn't generate the dist directory.
node index.ms build
- will work.dist folder should be created with relevant files, and the process should be exited with code 0.
3.27.1
2.3.1
16.13.2
Windows
11
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
https://github.com/Rezvitsky/vitejs-ssr
No response
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
3.26.0
2.3.1
14.18.3
macOS
12.0.1
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)
node app.mjs
No error to show and page to render
3.25.3
3.0.0
16.13.1
macOS
11.6 (Big Sur)
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
~/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'
]
}
It to build and run correctly.
Hi there!
I have a couple of thoughts about getting started.
import.meta.url
- I have never seen this before and it's hard to google.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
I want the initial setup experience for newcomers to be really easy.
It's a documentation thing.
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:
const minCriticalCss = {
style: [{
type: 'text/css',
children: '<important content>'
}]
};
minCriticalCss
to useHead
call.But, it is obviously akward to maintain. What alternativies can you recommend ?
3.29.0
3.0.0-beta.21
16.15.1
Windows
10
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
Copy vue-stream example to a windows machine and try to use
No response
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.
And finally, along the same lines:
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):
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.
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).
to reduce the bundle size and to remove, and not expose code that runs on the backend.
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.
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.
Ensuring Vite config loading goes through the Fastify plugin allows for dynamic changes.
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.
No response
3.x
3.x
16.x
Linux
11.0.1
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.
Run process.exit() after Fastify server started.
Exit code 0
Hi There.
I'd like to write unit tests for my Vue3 SFC components in my fastify-vite app.
I tried to use:
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.
Would you be interested to support Pug or how i do?
I see in Vite Pug works fine, but not with fastify-vite.
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 }}'
})
}
I should do the data formatting in the reply({}), yes?
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)
BTW this is so cool. I was so interested in Fastly, so to have this pushed me over the edge to dive deep.
compile the server app into mjs
file instead of cjs
.
mjs
has top-level await
like the browser also has, and it's much more consistent.
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
3.27.4
No response
16.14.0
Linux
PopOS 21.10
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
I give a reproduction repository : https://github.com/qlaffont-flexper/fastify-solid-vite-example
No response
3.25.0
3.0.0-alpha.2
14.x
Linux
Linux Mint 20.2 (Uma)
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:
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.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..
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.
No response
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
failed to load module for ssr: ${url}
);A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.