diff --git a/packages/nuxt/src/pages/page-meta.ts b/packages/nuxt/src/pages/page-meta.ts index e4a76cf28a4..bb53f1bf503 100644 --- a/packages/nuxt/src/pages/page-meta.ts +++ b/packages/nuxt/src/pages/page-meta.ts @@ -2,7 +2,7 @@ import { pathToFileURL } from 'node:url' import { createUnplugin } from 'unplugin' import { parseQuery, parseURL, stringifyQuery } from 'ufo' import { findStaticImports, findExports, StaticImport, parseStaticImport } from 'mlly' -import type { CallExpression, Expression } from 'estree' +import type { CallExpression, Identifier, Expression } from 'estree' import { walk } from 'estree-walker' import MagicString from 'magic-string' import { isAbsolute, normalize } from 'pathe' @@ -93,6 +93,7 @@ export const PageMetaPlugin = createUnplugin((options: PageMetaPluginOptions) => } const importMap = new Map() + const addedImports = new Set() for (const i of imports) { const parsed = parseStaticImport(i) for (const name of [ @@ -118,14 +119,25 @@ export const PageMetaPlugin = createUnplugin((options: PageMetaPluginOptions) => let contents = `const __nuxt_page_meta = ${code!.slice(meta.start, meta.end) || '{}'}\nexport default __nuxt_page_meta` + function addImport (name: string | false) { + if (name && importMap.has(name)) { + const importValue = importMap.get(name)!.code + if (!addedImports.has(importValue)) { + contents = importMap.get(name)!.code + '\n' + contents + addedImports.add(importValue) + } + } + } + walk(meta, { enter (_node) { if (_node.type === 'CallExpression') { const node = _node as CallExpression & { start: number, end: number } - const name = 'name' in node.callee && node.callee.name - if (name && importMap.has(name)) { - contents = importMap.get(name)!.code + '\n' + contents - } + addImport('name' in node.callee && node.callee.name) + } + if (_node.type === 'Identifier') { + const node = _node as Identifier & { start: number, end: number } + addImport(node.name) } } }) diff --git a/test/fixtures/basic/pages/index.vue b/test/fixtures/basic/pages/index.vue index f7af0739460..7935e551b09 100644 --- a/test/fixtures/basic/pages/index.vue +++ b/test/fixtures/basic/pages/index.vue @@ -23,6 +23,7 @@