Skip to content

Commit

Permalink
feat: ease Nuxt 4 update by removing app/ prefix from Prismic files
Browse files Browse the repository at this point in the history
  • Loading branch information
lihbr committed Jun 12, 2024
1 parent db3cac6 commit e0669de
Show file tree
Hide file tree
Showing 12 changed files with 252 additions and 50 deletions.
6 changes: 3 additions & 3 deletions docs/content/2.guides/2.advanced/1.custom-client.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@ description: ''

# Custom Client

You can make the module use your own [`@prismicio/client`](https://prismic.io/docs/technical-reference/prismicio-client?utm_campaign=devexp&utm_source=nuxt3doc&utm_medium=doc) instance. To do so, export it from `~/app/prismic/client`:
You can make the module use your own [`@prismicio/client`](https://prismic.io/docs/technical-reference/prismicio-client?utm_campaign=devexp&utm_source=nuxt3doc&utm_medium=doc) instance. To do so, export it from `~/prismic/client` (`~/app/prismic/client` on Nuxt 3):

```javascript [~/app/prismic/client.[jt]s]
```javascript [~/prismic/client.[jt]s]
import { createClient } from '@prismicio/client'

export default createClient('my-repository')
```

::alert{type="info"}
The default path (`~/app/prismic/client`) can be changed with the `client` option. See the [module configuration](/configuration#client) ->
The default path (`~/prismic/client`, `~/app/prismic/client` on Nuxt 3) can be changed with the `client` option. See the [module configuration](/configuration#client) ->
::
6 changes: 3 additions & 3 deletions docs/content/2.guides/2.advanced/2.link-resolver.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ description: ''
We recommend you use the more modern [Route Resolver](https://prismic.io/docs/route-resolver) whenever possible over the Link Resolver. We now only recommend to use the Link Resolver as an escape hatch.
::

You can make the module use a [Link Resolver](https://prismic.io/docs/core-concepts/link-resolver-route-resolver?utm_campaign=devexp&utm_source=nuxt3doc&utm_medium=doc#link-resolver). To do so, export one from `~/app/prismic/linkResolver`:
You can make the module use a [Link Resolver](https://prismic.io/docs/core-concepts/link-resolver-route-resolver?utm_campaign=devexp&utm_source=nuxt3doc&utm_medium=doc#link-resolver). To do so, export one from `~/prismic/linkResolver` (`~/app/prismic/linkResolver` on Nuxt 3):

```javascript [~/app/prismic/linkResolver.[jt]s]
```javascript [~/prismic/linkResolver.[jt]s]
export default (doc) => {
if (doc.type === 'page') {
return `/${doc.uid}`
Expand All @@ -20,5 +20,5 @@ export default (doc) => {
```

::alert{type="info"}
The default path (`~/app/prismic/linkResolver`) can be changed with the `linkResolver` option. See the [module configuration](/configuration#linkresolver) ->
The default path (`~/prismic/linkResolver`, `~/app/prismic/linkResolver` on Nuxt 3) can be changed with the `linkResolver` option. See the [module configuration](/configuration#linkresolver) ->
::
6 changes: 3 additions & 3 deletions docs/content/2.guides/2.advanced/3.rich-text-serializer.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@ description: ''

# Rich Text Serializer

You can make the module use a [Rich Text Serializer](https://prismic.io/docs/core-concepts/html-serializer?utm_campaign=devexp&utm_source=nuxt3doc&utm_medium=doc). To do so, export one from `~/app/prismic/richTextSerializer`:
You can make the module use a [Rich Text Serializer](https://prismic.io/docs/core-concepts/html-serializer?utm_campaign=devexp&utm_source=nuxt3doc&utm_medium=doc). To do so, export one from `~/prismic/richTextSerializer` (`~/app/prismic/richTextSerializer` on Nuxt 3):

```javascript [~/app/prismic/richTextSerializer.[jt]s]
```javascript [~/prismic/richTextSerializer.[jt]s]
export default {
paragraph: ({ children }) => `<p class="fooBar">${children}</p>`,
}
```

::alert{type="info"}
The default path (`~/app/prismic/richTextSerializer`) can be changed with the `richTextSerializer` option. See the [module configuration](/configuration#richtextserializer) ->
The default path (`~/prismic/richTextSerializer`, `~/app/prismic/richTextSerializer` on Nuxt 3) can be changed with the `richTextSerializer` option. See the [module configuration](/configuration#richtextserializer) ->
::
24 changes: 12 additions & 12 deletions docs/content/3.configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@ type PrismicModuleOptions = PrismicPluginOptions & {

```typescript[Defaults]
{
client: '~/app/prismic/client',
linkResolver: '~/app/prismic/linkResolver',
richTextSerializer: '~/app/prismic/richTextSerializer',
client: '~/prismic/client', // `~/app/prismic/client` on Nuxt 3
linkResolver: '~/prismic/linkResolver', // `~/app/prismic/linkResolver` on Nuxt 3
richTextSerializer: '~/prismic/richTextSerializer', // `~/app/prismic/richTextSerializer` on Nuxt 3
injectComponents: true,
preview: '/preview',
toolbar: true
Expand All @@ -49,15 +49,15 @@ type PrismicModuleOptions = PrismicPluginOptions & {

## Overview

| **Key** | **Type** | **Default** | **Description** |
| -------------------------------------------------- | ------------------- | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`...PrismicPluginOptions`](#prismicpluginoptions) | `object` | `{}` | Options provided to Prismic Vue plugin, see section below for more details. |
| `client` | `string` | `~/app/prismic/client` | Path to an optional file exporting an `@prismicio/client` instance for the module to use. |
| `linkResolver` | `string` | `~/app/prismic/linkResolver` | Path to an optional file exporting a [Link Resolver](https://prismic.io/docs/core-concepts/link-resolver-route-resolver?utm_campaign=devexp&utm_source=nuxt3doc&utm_medium=doc#link-resolver) for the module to use. |
| `richTextSerializer` | `string` | `~/app/prismic/richTextSerializer` | Path to an optional file exporting a [HTML Serializer](https://prismic.io/docs/core-concepts/html-serializer?utm_campaign=devexp&utm_source=nuxt3doc&utm_medium=doc) for the module to use. |
| `preview` | `string \| false` | `/preview` | The route to use for the preview page, disable previews with `false`. |
| `toolbar` | `boolean` | `true` | Whether or not to inject Prismic toolbar, required for previews to work properly. |
| `devtools` | `boolean` | `true` | Whether or not to enable the devtools UI. |
| **Key** | **Type** | **Default** | **Description** |
| -------------------------------------------------- | ------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`...PrismicPluginOptions`](#prismicpluginoptions) | `object` | `{}` | Options provided to Prismic Vue plugin, see section below for more details. |
| `client` | `string` | `~/prismic/client` <br /> _(`~/app/prismic/client` on Nuxt 3)_ | Path to an optional file exporting an `@prismicio/client` instance for the module to use. |
| `linkResolver` | `string` | `~/prismic/linkResolver` <br /> _(`~/app/prismic/linkResolver` on Nuxt 3)_ | Path to an optional file exporting a [Link Resolver](https://prismic.io/docs/core-concepts/link-resolver-route-resolver?utm_campaign=devexp&utm_source=nuxt3doc&utm_medium=doc#link-resolver) for the module to use. |
| `richTextSerializer` | `string` | `~/prismic/richTextSerializer` <br /> _(`~/app/prismic/richTextSerializer` on Nuxt 3)_ | Path to an optional file exporting a [HTML Serializer](https://prismic.io/docs/core-concepts/html-serializer?utm_campaign=devexp&utm_source=nuxt3doc&utm_medium=doc) for the module to use. |
| `preview` | `string \| false` | `/preview` | The route to use for the preview page, disable previews with `false`. |
| `toolbar` | `boolean` | `true` | Whether or not to inject Prismic toolbar, required for previews to work properly. |
| `devtools` | `boolean` | `true` | Whether or not to enable the devtools UI. |

## `...PrismicPluginOptions`

Expand Down
File renamed without changes.
9 changes: 4 additions & 5 deletions playground/nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,11 @@ import { startSubprocess } from '@nuxt/devtools-kit'

// https://v3.nuxtjs.org/docs/directory-structure/nuxt.config
export default defineNuxtConfig({
devtools: {
enabled: true,
},
typescript: {
strict: true,
future: {
compatibilityVersion: 4,
},
devtools: { enabled: true },
typescript: { strict: true },
modules: [
'../src/module',
/**
Expand Down
45 changes: 32 additions & 13 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
addImports,
addComponent,
extendPages,
getNuxtVersion,
} from '@nuxt/kit'

import * as prismicVue from '@prismicio/vue'
Expand Down Expand Up @@ -39,19 +40,37 @@ export default defineNuxtModule<PrismicModuleOptions>({
configKey: 'prismic',
compatibility: { nuxt: '>=3.7.0' },
},
defaults: _nuxt => ({
endpoint: '',
environment: '',
clientConfig: {},
client: '~/app/prismic/client',
linkResolver: '~/app/prismic/linkResolver',
richTextSerializer: '~/app/prismic/richTextSerializer',
injectComponents: true,
components: {},
preview: '/preview',
toolbar: true,
devtools: true,
}),
defaults: (nuxt) => {
let prismicFiles = {
client: '~/app/prismic/client',
linkResolver: '~/app/prismic/linkResolver',
richTextSerializer: '~/app/prismic/richTextSerializer',
}

// Nuxt 4 sets `app` as its `srcDir`, so we're just using the `prismic` folder there.
if (
nuxt.options?.future?.compatibilityVersion === 4
|| getNuxtVersion(nuxt).startsWith('4')
) {
prismicFiles = {
client: '~/prismic/client',
linkResolver: '~/prismic/linkResolver',
richTextSerializer: '~/prismic/richTextSerializer',
}
}

return {
endpoint: '',
environment: '',
clientConfig: {},
...prismicFiles,
injectComponents: true,
components: {},
preview: '/preview',
toolbar: true,
devtools: true,
}
},
hooks: {},
setup(options, nuxt) {
// Expose options through public runtime config
Expand Down
21 changes: 19 additions & 2 deletions test/__testutils__/mockedNuxtKit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ import { vi } from 'vitest'

import type { Nuxt } from '@nuxt/schema'

export const mockedNuxtKit = async () => {
export const mockedNuxtKit = async (mockOptions?: { nuxt4?: boolean }) => {
const kit: Record<string, unknown> = await vi.importActual('@nuxt/kit')

return {
...kit,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
defineNuxtModule: (definition: any) => (options = {}) => {
const mockedNuxt = {
let mockedNuxt = {
options: {
rootDir: '/tmp/nuxt',
srcDir: '/tmp/nuxt',
Expand All @@ -23,6 +23,23 @@ export const mockedNuxtKit = async () => {
version: '3.0.0',
} as unknown as Nuxt

if (mockOptions?.nuxt4) {
mockedNuxt = {
options: {
future: { compatibilityVersion: 4 },
rootDir: '/tmp/nuxt',
srcDir: '/tmp/nuxt/app',
dir: { app: 'app', pages: 'pages' },
build: { transpile: [] },
vite: {},
runtimeConfig: {},
app: { head: {} },
alias: {},
},
version: '3.0.0',
} as unknown as Nuxt
}

const mergedOptions = {
...definition.defaults(mockedNuxt),
...options,
Expand Down
2 changes: 1 addition & 1 deletion test/module-preview.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ it('injects default preview page', () => {
mockedPrismicModule({ endpoint: 'qwerty' })

expect(extendPages).toHaveBeenCalledOnce()
expect(vi.mocked(extendPages).mock.results[0].value.find((route: { name: string }) => route.name === 'prismic-preview')).toBeDefined()
expect(vi.mocked(extendPages).mock.results[0]?.value.find((route: { name: string }) => route.name === 'prismic-preview')).toBeDefined()
})

it('uses user preview when avaiable', () => {
Expand Down
138 changes: 138 additions & 0 deletions test/module-userFileProxy--nuxt4.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import { it, expect, vi, afterEach } from 'vitest'
import { vol } from 'memfs'

import { addTemplate } from '@nuxt/kit'

import prismicModule from '../src/module'

import { mockModule } from './__testutils__/mockModule'

const mockedPrismicModule = mockModule(prismicModule)

vi.mock('../src/lib/logger.ts', () => ({
logger: { info: vi.fn(), warn: vi.fn() },
}))
vi.mock('@nuxt/kit', async () => {
const { mockedNuxtKit } = await vi.importActual<typeof import('./__testutils__/mockedNuxtKit')>('./__testutils__/mockedNuxtKit')

return mockedNuxtKit({ nuxt4: true })
})

afterEach(() => {
vi.clearAllMocks()
})

it('proxies nothing if user files are not available', () => {
mockedPrismicModule({ endpoint: 'qwerty' })

expect(addTemplate).toHaveBeenCalledTimes(3)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect(vi.mocked(addTemplate).mock.calls.flat().map((options: any) => [options.filename, options.getContents()])).toMatchInlineSnapshot(`
[
[
"prismic/proxy/client.ts",
"export default undefined",
],
[
"prismic/proxy/linkResolver.ts",
"export default undefined",
],
[
"prismic/proxy/richTextSerializer.ts",
"export default undefined",
],
]
`)
})

it('proxies user files from default location', () => {
vol.fromJSON({
'/tmp/nuxt/app/prismic/client.ts': '',
'/tmp/nuxt/app/prismic/linkResolver.ts': '',
'/tmp/nuxt/app/prismic/richTextSerializer.ts': '',
})

mockedPrismicModule({ endpoint: 'qwerty' })

expect(addTemplate).toHaveBeenCalledTimes(3)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect(vi.mocked(addTemplate).mock.calls.flat().map((options: any) => [options.filename, options.getContents()])).toMatchInlineSnapshot(`
[
[
"prismic/proxy/client.ts",
"export { default } from '~/prismic/client'",
],
[
"prismic/proxy/linkResolver.ts",
"export { default } from '~/prismic/linkResolver'",
],
[
"prismic/proxy/richTextSerializer.ts",
"export { default } from '~/prismic/richTextSerializer'",
],
]
`)
})

it('proxies user files from default location (Nuxt 4)', () => {
vol.fromJSON({
'/tmp/nuxt/app/prismic/client.ts': '',
'/tmp/nuxt/app/prismic/linkResolver.ts': '',
'/tmp/nuxt/app/prismic/richTextSerializer.ts': '',
})

mockedPrismicModule({ endpoint: 'qwerty' })

expect(addTemplate).toHaveBeenCalledTimes(3)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect(vi.mocked(addTemplate).mock.calls.flat().map((options: any) => [options.filename, options.getContents()])).toMatchInlineSnapshot(`
[
[
"prismic/proxy/client.ts",
"export { default } from '~/prismic/client'",
],
[
"prismic/proxy/linkResolver.ts",
"export { default } from '~/prismic/linkResolver'",
],
[
"prismic/proxy/richTextSerializer.ts",
"export { default } from '~/prismic/richTextSerializer'",
],
]
`)
})

it('proxies user files from provided location', () => {
vol.fromJSON({
'/tmp/nuxt/app/custom/client.ts': '',
'/tmp/nuxt/app/custom/linkResolver.ts': '',
'/tmp/nuxt/app/custom/richTextSerializer.ts': '',
})

mockedPrismicModule({
endpoint: 'qwerty',
client: '~/custom/client',
linkResolver: '~/custom/linkResolver',
richTextSerializer: '~/custom/richTextSerializer',
})

expect(addTemplate).toHaveBeenCalledTimes(3)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect(vi.mocked(addTemplate).mock.calls.flat().map((options: any) => [options.filename, options.getContents()])).toMatchInlineSnapshot(`
[
[
"prismic/proxy/client.ts",
"export { default } from '~/custom/client'",
],
[
"prismic/proxy/linkResolver.ts",
"export { default } from '~/custom/linkResolver'",
],
[
"prismic/proxy/richTextSerializer.ts",
"export { default } from '~/custom/richTextSerializer'",
],
]
`)
})
29 changes: 29 additions & 0 deletions test/module-userFileProxy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,35 @@ it('proxies user files from default location', () => {
`)
})

it('proxies user files from default location (Nuxt 4)', () => {
vol.fromJSON({
'/tmp/nuxt/app/prismic/client.ts': '',
'/tmp/nuxt/app/prismic/linkResolver.ts': '',
'/tmp/nuxt/app/prismic/richTextSerializer.ts': '',
})

mockedPrismicModule({ endpoint: 'qwerty' })

expect(addTemplate).toHaveBeenCalledTimes(3)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect(vi.mocked(addTemplate).mock.calls.flat().map((options: any) => [options.filename, options.getContents()])).toMatchInlineSnapshot(`
[
[
"prismic/proxy/client.ts",
"export { default } from '~/app/prismic/client'",
],
[
"prismic/proxy/linkResolver.ts",
"export { default } from '~/app/prismic/linkResolver'",
],
[
"prismic/proxy/richTextSerializer.ts",
"export { default } from '~/app/prismic/richTextSerializer'",
],
]
`)
})

it('proxies user files from provided location', () => {
vol.fromJSON({
'/tmp/nuxt/custom/client.ts': '',
Expand Down
Loading

0 comments on commit e0669de

Please sign in to comment.