Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 91 additions & 18 deletions .storybook/main.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import type { StorybookConfig } from '@storybook-vue/nuxt'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'

const config = {
stories: [
Expand All @@ -21,29 +23,95 @@ const config = {
async viteFinal(newConfig) {
newConfig.plugins ??= []

// Fix: nuxt:components:imports-alias relies on internal Nuxt state that is
// cleaned up after nuxt.close() in @storybook-vue/nuxt's loadNuxtViteConfig.
// When that state is gone, `import X from '#components'` is left unresolved
// and Vite 8 falls through to package-subpath resolution, which fails with
// "Missing '#components' specifier in 'nuxt' package".
// This plugin intercepts #components first and serves a virtual module built
// from the components.d.ts written during the same Nuxt boot.
// Resolve the Nuxt build dir from Vite's alias map, which can be either a
// plain-object (Record<string, string>) or Vite's resolved array form
// (readonly Alias[] where find is string | RegExp). We must handle both
// without casting to Record<string, string>, which would be unsound for the
// array form.
Comment on lines +26 to +37
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel like everytime we add new stories for pages we have to patch storybook 😆 worth it though!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also I think this is the thing that has been stopping me from being able to run storybook locally, so will try again later 🫡

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I'm hopeful that some of these are resolved when there is a SB v10 version for @storybook-vue/nuxt but might need to upstream some of these or at least open some issues for them if not.

const aliases = newConfig.resolve?.alias
const buildDir = (() => {
if (!aliases) return undefined
if (Array.isArray(aliases)) {
const entry = aliases.find(a => a.find === '#build')
return typeof entry?.replacement === 'string' ? entry.replacement : undefined
}
const value = (aliases as Record<string, unknown>)['#build']
return typeof value === 'string' ? value : undefined
})()
newConfig.plugins.unshift({
name: 'storybook-nuxt-components',
enforce: 'pre',
resolveId(id) {
if (id === '#components') return '\0virtual:#components'
return null
},
load(id) {
if (id !== '\0virtual:#components') return
if (!buildDir) {
throw new Error('[storybook-nuxt-components] Could not resolve the `#build` alias.')
}
const dtsPath = resolve(buildDir, 'components.d.ts')
// Wire the generated declaration file into Vite's file-watch graph so
// that the virtual module is invalidated when Nuxt regenerates it.
this.addWatchFile(dtsPath)
const dts = readFileSync(dtsPath, 'utf-8')
const lines: string[] = []
// Match only the direct `typeof import("…").default` form.
// Lazy/island wrappers (LazyComponent<T>, IslandComponent<T>) are
// excluded intentionally — Storybook only needs the concrete type.
// The format has been stable across all Nuxt 3 releases.
const re =
/^export const (\w+): typeof import\("([^"]+)"\)(?:\.default|\[['"]default['"]\])\s*;?$/gm
let match: RegExpExecArray | null
while ((match = re.exec(dts)) !== null) {
const [, name, rel] = match
if (!name || !rel) continue
const abs = resolve(buildDir, rel).replaceAll('\\', '/')
lines.push(`export { default as ${name} } from ${JSON.stringify(abs)}`)
}
if (lines.length === 0) {
throw new Error(
`[storybook-nuxt-components] No component exports were found in ${dtsPath}.`,
)
}
return lines.join('\n')
},
})

// Bridge compatibility between Storybook v10 core and v9 @storybook-vue/nuxt
// v10 expects module federation globals that v9 doesn't provide
newConfig.plugins.push({
name: 'storybook-v10-compat',
transformIndexHtml: {
order: 'pre',
handler(html) {
const script = `
<script>
// Minimal shims for Storybook v10 module federation system
// These will be replaced when Storybook runtime loads
window.__STORYBOOK_MODULE_GLOBAL__ = { global: window };
window.__STORYBOOK_MODULE_CLIENT_LOGGER__ = {
deprecate: console.warn.bind(console, '[deprecated]'),
once: console.log.bind(console),
logger: console
};
window.__STORYBOOK_MODULE_CHANNELS__ = {
Channel: class { on() {} off() {} emit() {} once() {} },
createBrowserChannel: () => new window.__STORYBOOK_MODULE_CHANNELS__.Channel()
};
</script>`
return html.replace(/<script>/, script + '<script>')
handler() {
return [
{
tag: 'script',
injectTo: 'head-prepend' as const,
children: [
'// Minimal shims for Storybook v10 module federation system',
'// These will be replaced when Storybook runtime loads',
'window.__STORYBOOK_MODULE_GLOBAL__ = { global: window };',
'window.__STORYBOOK_MODULE_CLIENT_LOGGER__ = {',
" deprecate: console.warn.bind(console, '[deprecated]'),",
' once: console.log.bind(console),',
' logger: console',
'};',
'window.__STORYBOOK_MODULE_CHANNELS__ = {',
' Channel: class { on() {} off() {} emit() {} once() {} },',
' createBrowserChannel: () => new window.__STORYBOOK_MODULE_CHANNELS__.Channel()',
'};',
].join('\n'),
},
]
},
},
})
Expand Down Expand Up @@ -73,7 +141,12 @@ const config = {
const wrapped = async function (this: unknown, ...args: unknown[]) {
try {
return await originalFn.apply(this, args)
} catch {
} catch (err) {
// oxlint-disable-next-line no-console -- Log and swallow errors to avoid breaking the Storybook build when vue-docgen-api encounters an unparseable component.
console.warn(
'[storybook:vue-docgen-plugin] Suppressed docgen error (component docs may be missing):',
err,
)
return undefined
}
}
Expand Down
16 changes: 16 additions & 0 deletions app/pages/brand.stories.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import Brand from './brand.vue'
import type { Meta, StoryObj } from '@storybook-vue/nuxt'
import { pageDecorator } from '../../.storybook/decorators'

const meta = {
component: Brand,
parameters: {
layout: 'fullscreen',
},
decorators: [pageDecorator],
} satisfies Meta<typeof Brand>

export default meta
type Story = StoryObj<typeof meta>

export const Default: Story = {}
Loading