Skip to content
This repository has been archived by the owner on Nov 23, 2023. It is now read-only.

Commit

Permalink
Merge pull request #16 from fastify/vue-support
Browse files Browse the repository at this point in the history
feat: Vue support
  • Loading branch information
galvez authored Jun 20, 2022
2 parents b583f01 + 706489d commit 2cd88af
Show file tree
Hide file tree
Showing 49 changed files with 2,302 additions and 3 deletions.
58 changes: 58 additions & 0 deletions docs/vue/basic-setup.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<sub>**Go back to the [index](https://github.com/fastify/fastify-dx/blob/main/packages/fastify-dx-vue/README.md).**</sub>

<br>

## Basic setup

The [starter template](https://github.com/fastify/fastify-dx/tree/dev/starters/vue) follows [fastify-vite](https://github.com/fastify/fastify-vite)'s convention of having a `client` folder with an `index.js` file, which is automatically resolved as your `clientModule` setting.

If you want flat directory setup, where server and client files are mixed together, you can manually set `clientModule` to something else. Note that in this case you'll also need to update `root` in your `vite.config.js` file.

When deploying to production, bear in mind the `client/dist` directory, generated when you run `npm run build`, needs to be included. You'll also want to enable Fastify's [built-in logging](https://www.fastify.io/docs/latest/Reference/Logging/):

```js
const server = Fastify({ logger: true })
```

The starter template's `server.js` file:

```js
import Fastify from 'fastify'
import FastifyVite from 'fastify-vite'
import FastifyDXVue from 'fastify-dx-vue'

const server = Fastify()

await server.register(FastifyVite, {
root: import.meta.url,
renderer: FastifyDXVue,
})

await server.vite.ready()
await server.listen(3000)
```

The starter template's [`vite.config.js`](https://github.com/fastify/fastify-dx/blob/main/starters/vue/vite.config.js) file:

```js
import viteVue from '@vitejs/plugin-vue'
import viteVueFastifyDX from 'fastify-dx-vue/plugin'
import unocss from 'unocss/vite'

const path = fileURLToPath(import.meta.url)

const root = join(dirname(path), 'client')
const plugins = [
viteVue(),
viteVueFastifyDX(),
unocss()
]

export default { root, plugins }
```
Note that you only need to use Fastify DX's Vite plugin, which includes all functionality from [fastify-vite](https://github.com/fastify/fastify-vite)'s Vite plugin.
</td>
</tr>
</table>
36 changes: 36 additions & 0 deletions docs/vue/data-prefetching.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<sub>**Go back to the [index](https://github.com/fastify/fastify-dx/blob/main/packages/fastify-dx-vue/README.md).**</sub>

<br>

## Isomorphic data prefetching

Fastify DX for Vue implements the `getData()` hook from the [URMA specification](https://github.com/fastify/fastify-dx/blob/main/URMA.md) to solve this problem.

### `getData(ctx)`

This hook is set up in a way that it runs server-side before any SSR takes place, so any data fetched is made available to the route component before it starts rendering. During first render, any data retrieved on the server is automatically sent to be hydrated on the client so no new requests are made. Then, during client-side navigation (post first-render), a JSON request is fired to an endpoint automatically registered for running the `getData()` function for that route on the server.

The objet returned by `getData()` gets automatically assigned as `data` in the [universal route context](https://github.com/fastify/fastify-dx/blob/main/docs/vue/route-context.md) object and is accessible from `getMeta()` and `onEnter()` hooks and also via the `useRouteContext()` hook.

```vue
<template>
<p>{data.message}</p>
</template>
<script>
import { useRouteContext } from '/dx:core.js'
export function getData (ctx) {
return {
message: 'Hello from getData!',
}
}
export default {
setup () {
const { data } = useRouteContext()
return { data }
}
}
</script>
```
93 changes: 93 additions & 0 deletions docs/vue/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
# fastify-dx-vue [![NPM version](https://img.shields.io/npm/v/fastify-dx-vue.svg?style=flat)](https://www.npmjs.com/package/fastify-dx-vue) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://standardjs.com/)

- [**Introduction**](https://github.com/fastify/fastify-dx/blob/main/packages/fastify-dx-vue/README.md#introduction)
- [**Quick Start**](https://github.com/fastify/fastify-dx/blob/main/packages/fastify-dx-vue/README.md#quick-start)
- [**Package Scripts**](https://github.com/fastify/fastify-dx/blob/main/packages/fastify-dx-vue/README.md#package-scripts)
- [**Basic Setup**](https://github.com/fastify/fastify-dx/blob/main/docs/vue/basic-setup.md)
- [**Project Structure**](https://github.com/fastify/fastify-dx/blob/main/docs/vue/project-structure.md)
- [**Rendering Modes**](https://github.com/fastify/fastify-dx/blob/main/docs/vue/rendering-modes.md)
- [**Routing Configuration**](https://github.com/fastify/fastify-dx/blob/main/docs/vue/routing-config.md)
- [**Data Prefetching**](https://github.com/fastify/fastify-dx/blob/main/docs/vue/data-prefetching.md)
- [**Route Layouts**](https://github.com/fastify/fastify-dx/blob/main/docs/vue/route-layouts.md)
- [**Route Context**](https://github.com/fastify/fastify-dx/blob/main/docs/vue/route-context.md)
- [**Route Enter Event**](https://github.com/fastify/fastify-dx/blob/main/docs/vue/route-enter.md)
- [**Virtual Modules**](https://github.com/fastify/fastify-dx/blob/main/docs/vue/virtual-modules.md)

## Introduction

**Fastify DX for Vue** is a renderer adapter for [**fastify-vite**](https://github.com/fastify/fastify-vite).

It lets you run and SSR (server-side render) **Vue 3 applications built with Vite** on [Fastify](https://fastify.io/), with a minimal and transparent **server-first approach** — everything starts with `server.js`, your actual Fastify server).

It also provides a set of built-in utilities for ease of development and managing a universal JavaScript context (SSR to CSR), very much like **Nuxt.js**, **Next.js** and **Remix**. Both **Fastify DX for Vue** and [**Fastify DX for React**](https://github.com/fastify/fastify-dx/tree/main/packages/fastify-dx-react) implement the [URMA specification](https://github.com/fastify/fastify-dx/blob/main/URMA.md) and have almost the same API, with only minimal differences due to specific framework APIs or idioms.

It is a **fast**, **lightweight** alternative to Nuxt.js packed with **Developer Experience** features.

It has an extremely small core (~1k LOC total) and is built on top of [Fastify](https://github.com/fastify/fastify), [Vite](https://vitejs.dev/) and [Vue Router](https://router.vuejs.org/).

[**See the release notes for the 0.0.1 alpha release**](https://github.com/fastify/fastify-dx/releases/tag/vue-v0.0.1).

> At this stage this project is mostly a [**one-man show**](https://github.com/sponsors/galvez), who's devoting all his free time to its completion. Contributions are extremely welcome, as well as bug reports for any issues you may find.
In this first alpha release it's still missing a test suite. The same is true for [**fastify-vite**]().

It'll move into **beta** status when test suites are added to both packages.

## Quick Start

Ensure you have **Node v16+**.

Make a copy of [**starters/vue**](https://github.com/fastify/fastify-dx/tree/dev/starters/vue). If you have [`degit`](https://github.com/Rich-Harris/degit), run the following from a new directory:

```bash
degit fastify/fastify-dx/starters/vue
```

> **If you're starting a project from scratch**, you'll need these packages installed.
>
> ```bash
> npm i fastify fastify-vite fastify-dx-vue -P
> npm i @vitejs/plugin-vue -D
> ```
Run `npm install`.
Run `npm run dev`.
Visit `http://localhost:3000/`.
## What's Included
That will get you a **starter template** with:
- A minimal [Fastify](https://github.com/fastify/fastify) server.
- Some dummy API routes.
- A `pages/` folder with some [demo routes](https://github.com/fastify/fastify-dx/tree/dev/starters/vue/client/pages).
- All configuration files.
It also includes some _**opinionated**_ essentials:
- [**PostCSS Preset Env**](https://www.npmjs.com/package/postcss-preset-env) by [**Jonathan Neal**](https://github.com/jonathantneal), which enables [several modern CSS features](https://preset-env.cssdb.org/), such as [**CSS Nesting**](https://www.w3.org/TR/css-nesting-1/).
- [**UnoCSS**](https://github.com/unocss/unocss) by [**Anthony Fu**](https://antfu.me/), which supports all [Tailwind utilities](https://uno.antfu.me/) and many other goodies through its [default preset](https://github.com/unocss/unocss/tree/main/packages/preset-uno).
- [**VueUse**](https://vueuse.org/) by [**Anthony Fu**](https://antfu.me/), which provides an extremely rich set of utilities — they're not included in the project build unless explicitly imported and used.
## Package Scripts
`npm run dev` boots the development server.
`npm run build` creates the production bundle.
`npm run serve` serves the production bundle.
## Meta
Created by [Jonas Galvez](https://github.com/sponsors/galvez), **Engineering Manager** and **Open Sourcerer** at [NearForm](https://nearform.com).
## Sponsors
<a href="https://nearform.com"><img width="200px" src="https://user-images.githubusercontent.com/12291/172310344-594669fd-da4c-466b-a250-a898569dfea3.svg"></a>
Also [**Duc-Thien Bui**](https://github.com/aecea) and [**Tom Preston-Werner**](https://github.com/mojombo) [via GitHub Sponsors](https://github.com/sponsors/galvez). _Thank you!_
33 changes: 33 additions & 0 deletions docs/vue/meta-tags.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@

<sub>**Go back to the [index](https://github.com/fastify/fastify-dx/blob/main/packages/fastify-dx-vue/README.md).**</sub>

<br>

## Meta Tags

Following the [URMA specification](https://github.com/fastify/fastify-dx/blob/main/URMA.md), Fastify DX renders `<head>` elements independently from the SSR phase. This allows you to fetch data for populating the first `<meta>` tags and stream them right away to the client, and only then perform SSR.

> Additional `<link>` preload tags can be produced from the SSR phase. This is **not currently implemented** in this **alpha release** but is a planned feature. If you can't wait for it, you can roll out your own (and perhaps contribute your solution) by providing your own [`createHtmlFunction()`](https://github.com/fastify/fastify-dx/blob/main/packages/fastify-dx-vue/index.js#L57) to [fastify-vite](https://github.com/fastify/fastify-vite).
### `getMeta()`

To populate `<title>`, `<meta>` and `<link>` elements, export a `getMeta()` function that returns an object matching the format expected by [unihead](https://github.com/galvez/unihead), the underlying library used by Fastify DX.

It receives the [route context](https://github.com/fastify/fastify-dx/blob/main/packages/fastify-dx-vue/README.md#route-context) as first parameter and runs after `getData()`, allowing you to access any `data` populated by these other functions to generate your tags.

```vue
<template>
<p>Route with meta tags.</p>
</template>
<script>
export function getMeta (ctx) {
return {
title: 'Route Title',
meta: [
{ name: 'twitter:title', value: 'Route Title' },
]
}
}
</script>
```
63 changes: 63 additions & 0 deletions docs/vue/project-structure.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@

<sub>**Go back to the [index](https://github.com/fastify/fastify-dx/blob/main/packages/fastify-dx-vue/README.md).**</sub>

<br>

## Project Structure

The [starter template](https://github.com/fastify/fastify-dx/tree/dev/starters/vue) looks like this:

```
├── server.js
├── client/
| ├── index.js
| ├── context.js
| ├── root.vue
| ├── index.html
| ├── layouts/
| | ├── default.vue
| | └── auth.vue
| └── pages/
| ├── index.vue
| ├── client-only.vue
| ├── server-only.vue
| ├── streaming.vue
| ├── using-data.vue
| └── using-store.vue
├── vite.config.js
└── package.json
```

Several internal files are provided as virtual modules by Fastify DX. They are located inside the `fastify-dx-vue` package in `node_modules`, and dynamically loaded so you don't have to worry about them unless you want them overriden.

In this case, placing a file with the same name as the registered virtual module in your Vite project root will override it. Find the detailed rundown of all virtual modules [here][virtual-modules].

[virtual-modules]: https://github.com/fastify/fastify-dx/blob/main/docs/vue/virtual-modules.md

The `server.js` file is your application entry point. It's the file that runs everything. It boots a Fastify server configured with [**fastify-vite**](https://github.com/fastify/fastify-vite) and **Fastify DX for Vue** as a renderer adapter to **fastify-vite**.

The `client/index.js` file is your Vite server entry point, it's the file that provides your client bundle (which runs in the Vite-enriched environment) to the Node.js environment where Fastify runs.

> Right now, it's mostly a **boilerplate file** because it must exist but it will also probably never need to be changed.
It exports your application's factory function (must be named `create`), the application routes (must be named `routes`) and the universal route context [initialization module](https://github.com/fastify/fastify-dx/blob/main/docs/vue/route-context.md#initialization-module) (must be named `context` and have a dynamic module import so Fastify DX can pick up `default` and named exports).

The `client/index.html` file is the [root HTML template of the application](https://vitejs.dev/guide/#index-html-and-project-root), which Vite uses as the client bundling entry point.

> You can expand this file with additional `<meta>` and `<link>` tags if you wish, provided you don't remove any of the placeholders.
This files links to `/dx:mount.js`, which is a virtual module provided by Fastify DX.

Virtual modules are covered [here][virtual-modules].

The `client/pages/` directory contains your route modules, whose paths are dynamically inferred from the directory structure itself. You can change this behavior easily. More on this [here][routing-config].

[routing-config]: https://github.com/fastify/fastify-dx/blob/main/docs/vue/routing-config.md

The `client/layouts/` directory contains your route layout modules, which can be associated to any route. By default, `layouts/default.vue` is used, but if you don't need to do any modifications on that file, you can safely removed as it's provided by Fastify DX in that case. The starter template also comes with `layouts/auth.vue`, to demonstrate a more advanced use of layouts.

[routing-config]: https://github.com/fastify/fastify-dx/blob/main/docs/vue/routing-config.md

The `client/context.js` file is the universal [route context][route-context] initialization module. Any named exports from this file are attached to the `RouteContext` class prototype on the server, preventing them from being reassigned on every request. The `default` export from this file, however, runs for every request so you can attach any request-specific data to it.

[route-context]: https://github.com/fastify/fastify-dx/blob/main/docs/vue/route-context.md
69 changes: 69 additions & 0 deletions docs/vue/rendering-modes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@

<sub>**Go back to the [index](https://github.com/fastify/fastify-dx/blob/main/packages/fastify-dx-vue/README.md).**</sub>

<br>

# Rendering modes

Following the [URMA specification](https://github.com/fastify/fastify-dx/blob/main/URMA.md), Fastify DX's route modules can be set for universal rendering (SSR + CSR hydration, the default behavior), SSR in streaming mode, SSR only (client gets no JavaScript) or CSR only (SSR fully disabled).

## `streaming`

If a route module exports `streaming` set to `true`, SSR will take place in **streaming mode**. That means the result of all server-side rendering gets streamed as it takes place, even if you have asynchronous Vue components. Note that differently from React, Vue **will not** stream a Suspense block's `#fallback` template.

```vue
<template>
<Message :secs="2" />
<Message :secs="4" />
<Message :secs="6" />
</template>
<script>
import Message from '/components/Message.vue'
export const streaming = true
export default {
components: { Message },
}
</script>
```

[See the full example](https://github.com/fastify/fastify-dx/blob/main/starters/vue/client/pages/streaming.vue) in the [starter template](https://github.com/fastify/fastify-dx/tree/dev/starters/vue).


## `serverOnly`

If a route module exports `serverOnly` set to `true`, only SSR will take place. The client gets the server-side rendered markup without any accompanying JavaScript or data hydration.

You should use this setting to deliver lighter pages when there's no need to run any code on them, such as statically generated content sites.

```vue
<template>
<p>This route is rendered on the server only!</p>
</template>
<script>
export const serverOnly = true
</script>
```

[This example](https://github.com/fastify/fastify-dx/blob/main/starters/vue/client/pages/server-only.vue) is part of the [starter template](https://github.com/fastify/fastify-dx/tree/dev/starters/vue).

## `clientOnly`

If a route module exports `clientOnly` set to `true`, no SSR will take place, only data fetching and data hydration. The client gets the empty container element (the one that wraps `<!-- element -->` in `index.html`) and all rendering takes place on the client only.

You can use this setting to save server resources on internal pages where SSR makes no significant diference for search engines or UX in general, such as a password-protected admin section.

```vue
<template>
<p>This route is rendered on the client only!</p>
</template>
<script>
export const clientOnly = true
</script>
```

[This example](https://github.com/fastify/fastify-dx/blob/main/starters/vue/client/pages/client-only.vue) is part of the [starter template](https://github.com/fastify/fastify-dx/tree/dev/starters/vue).
Loading

0 comments on commit 2cd88af

Please sign in to comment.