fix(nuxt): respect esbuild options in transforms

This commit is contained in:
Daniel Roe 2024-06-18 17:24:05 +01:00
parent 8373c444fb
commit 07c9f7a6f8
No known key found for this signature in database
GPG Key ID: 3714AB03996F442B
7 changed files with 18 additions and 15 deletions

View File

@ -258,7 +258,7 @@ export async function annotatePlugins (nuxt: Nuxt, plugins: NuxtPlugin[]) {
try { try {
const code = plugin.src in nuxt.vfs ? nuxt.vfs[plugin.src] : await fsp.readFile(plugin.src!, 'utf-8') const code = plugin.src in nuxt.vfs ? nuxt.vfs[plugin.src] : await fsp.readFile(plugin.src!, 'utf-8')
_plugins.push({ _plugins.push({
...await extractMetadata(code, IS_TSX.test(plugin.src) ? 'tsx' : 'ts'), ...await extractMetadata(code, IS_TSX.test(plugin.src) ? 'tsx' : 'ts', nuxt.options.esbuild.options),
...plugin, ...plugin,
}) })
} catch (e) { } catch (e) {

View File

@ -87,7 +87,7 @@ export async function initNitro (nuxt: Nuxt & { _nitro?: Nitro }) {
esbuild: { esbuild: {
options: { options: {
exclude: excludePattern, exclude: excludePattern,
...nuxt.options.esbuild ...nuxt.options.esbuild.options
}, },
}, },
analyze: !nuxt.options.test && nuxt.options.build.analyze && (nuxt.options.build.analyze === true || nuxt.options.build.analyze.enabled) analyze: !nuxt.options.test && nuxt.options.build.analyze && (nuxt.options.build.analyze === true || nuxt.options.build.analyze.enabled)

View File

@ -2,6 +2,7 @@ import type { CallExpression, Literal, Property, SpreadElement } from 'estree'
import type { Node } from 'estree-walker' import type { Node } from 'estree-walker'
import { walk } from 'estree-walker' import { walk } from 'estree-walker'
import { transform } from 'esbuild' import { transform } from 'esbuild'
import type { TransformOptions } from 'esbuild'
import { parse } from 'acorn' import { parse } from 'acorn'
import { defu } from 'defu' import { defu } from 'defu'
import { findExports } from 'mlly' import { findExports } from 'mlly'
@ -41,12 +42,12 @@ export const orderMap: Record<NonNullable<ObjectPlugin['enforce']>, number> = {
} }
const metaCache: Record<string, Omit<PluginMeta, 'enforce'>> = {} const metaCache: Record<string, Omit<PluginMeta, 'enforce'>> = {}
export async function extractMetadata (code: string, loader = 'ts' as 'ts' | 'tsx') { export async function extractMetadata (code: string, loader = 'ts' as 'ts' | 'tsx', esbuildOptions?: TransformOptions) {
let meta: PluginMeta = {} let meta: PluginMeta = {}
if (metaCache[code]) { if (metaCache[code]) {
return metaCache[code] return metaCache[code]
} }
const js = await transform(code, { loader }) const js = await transform(code, { loader, ...esbuildOptions })
walk(parse(js.code, { walk(parse(js.code, {
sourceType: 'module', sourceType: 'module',
ecmaVersion: 'latest', ecmaVersion: 'latest',

View File

@ -37,7 +37,7 @@ export function prehydrateTransformPlugin (nuxt: Nuxt) {
const needsAttr = node.arguments[0].params.length > 0 const needsAttr = node.arguments[0].params.length > 0
const { start, end } = node.arguments[0] as Node & { start: number, end: number } const { start, end } = node.arguments[0] as Node & { start: number, end: number }
const p = transform(`forEach(${code.slice(start, end)})`, { loader: 'ts', minify: true }) const p = transform(`forEach(${code.slice(start, end)})`, { loader: 'ts', minify: true, ...nuxt.options.esbuild.options })
promises.push(p.then(({ code: result }) => { promises.push(p.then(({ code: result }) => {
const cleaned = result.slice('forEach'.length).replace(/;\s+$/, '') const cleaned = result.slice('forEach'.length).replace(/;\s+$/, '')
const args = [JSON.stringify(cleaned)] const args = [JSON.stringify(cleaned)]

View File

@ -303,7 +303,7 @@ export default defineNuxtModule({
const glob = pageToGlobMap[path] const glob = pageToGlobMap[path]
const code = path in nuxt.vfs ? nuxt.vfs[path] : await readFile(path!, 'utf-8') const code = path in nuxt.vfs ? nuxt.vfs[path] : await readFile(path!, 'utf-8')
try { try {
const extractedRule = await extractRouteRules(code) const extractedRule = await extractRouteRules(code, nuxt.options.esbuild.options)
if (extractedRule) { if (extractedRule) {
if (!glob) { if (!glob) {
const relativePath = relative(nuxt.options.srcDir, path) const relativePath = relative(nuxt.options.srcDir, path)

View File

@ -3,6 +3,7 @@ import type { Node } from 'estree-walker'
import type { CallExpression } from 'estree' import type { CallExpression } from 'estree'
import { walk } from 'estree-walker' import { walk } from 'estree-walker'
import { transform } from 'esbuild' import { transform } from 'esbuild'
import type { TransformOptions } from 'esbuild'
import { parse } from 'acorn' import { parse } from 'acorn'
import type { NuxtPage } from '@nuxt/schema' import type { NuxtPage } from '@nuxt/schema'
import type { NitroRouteConfig } from 'nitropack' import type { NitroRouteConfig } from 'nitropack'
@ -12,7 +13,7 @@ import { extractScriptContent, pathToNitroGlob } from './utils'
const ROUTE_RULE_RE = /\bdefineRouteRules\(/ const ROUTE_RULE_RE = /\bdefineRouteRules\(/
const ruleCache: Record<string, NitroRouteConfig | null> = {} const ruleCache: Record<string, NitroRouteConfig | null> = {}
export async function extractRouteRules (code: string): Promise<NitroRouteConfig | null> { export async function extractRouteRules (code: string, esbuildOptions?: TransformOptions): Promise<NitroRouteConfig | null> {
if (code in ruleCache) { if (code in ruleCache) {
return ruleCache[code] return ruleCache[code]
} }
@ -23,7 +24,7 @@ export async function extractRouteRules (code: string): Promise<NitroRouteConfig
let rule: NitroRouteConfig | null = null let rule: NitroRouteConfig | null = null
const js = await transform(code, { loader: script?.loader || 'ts' }) const js = await transform(code, { loader: script?.loader || 'ts', ...esbuildOptions })
walk(parse(js.code, { walk(parse(js.code, {
sourceType: 'module', sourceType: 'module',
ecmaVersion: 'latest', ecmaVersion: 'latest',

View File

@ -8,6 +8,7 @@ import escapeRE from 'escape-string-regexp'
import { filename } from 'pathe/utils' import { filename } from 'pathe/utils'
import { hash } from 'ohash' import { hash } from 'ohash'
import { transform } from 'esbuild' import { transform } from 'esbuild'
import type { TransformOptions } from 'esbuild'
import { parse } from 'acorn' import { parse } from 'acorn'
import { walk } from 'estree-walker' import { walk } from 'estree-walker'
import type { CallExpression, ExpressionStatement, ObjectExpression, Program, Property } from 'estree' import type { CallExpression, ExpressionStatement, ObjectExpression, Program, Property } from 'estree'
@ -67,9 +68,9 @@ export async function resolvePagesRoutes (): Promise<NuxtPage[]> {
const shouldAugment = nuxt.options.experimental.scanPageMeta || nuxt.options.experimental.typedPages const shouldAugment = nuxt.options.experimental.scanPageMeta || nuxt.options.experimental.typedPages
if (shouldAugment) { if (shouldAugment) {
const augmentedPages = await augmentPages(pages, nuxt.vfs) const augmentedPages = await augmentPages(pages, nuxt.vfs, undefined, nuxt.options.esbuild.options)
await nuxt.callHook('pages:extend', pages) await nuxt.callHook('pages:extend', pages)
await augmentPages(pages, nuxt.vfs, augmentedPages) await augmentPages(pages, nuxt.vfs, augmentedPages, nuxt.options.esbuild.options)
augmentedPages.clear() augmentedPages.clear()
} else { } else {
await nuxt.callHook('pages:extend', pages) await nuxt.callHook('pages:extend', pages)
@ -140,16 +141,16 @@ export function generateRoutesFromFiles (files: ScannedFile[], options: Generate
return prepareRoutes(routes) return prepareRoutes(routes)
} }
export async function augmentPages (routes: NuxtPage[], vfs: Record<string, string>, augmentedPages = new Set<string>()) { export async function augmentPages (routes: NuxtPage[], vfs: Record<string, string>, augmentedPages = new Set<string>(), esbuildOptions?: TransformOptions) {
for (const route of routes) { for (const route of routes) {
if (route.file && !augmentedPages.has(route.file)) { if (route.file && !augmentedPages.has(route.file)) {
const fileContent = route.file in vfs ? vfs[route.file] : fs.readFileSync(await resolvePath(route.file), 'utf-8') const fileContent = route.file in vfs ? vfs[route.file] : fs.readFileSync(await resolvePath(route.file), 'utf-8')
Object.assign(route, await getRouteMeta(fileContent, route.file)) Object.assign(route, await getRouteMeta(fileContent, route.file, esbuildOptions))
augmentedPages.add(route.file) augmentedPages.add(route.file)
} }
if (route.children && route.children.length > 0) { if (route.children && route.children.length > 0) {
await augmentPages(route.children, vfs) await augmentPages(route.children, vfs, augmentedPages, esbuildOptions)
} }
} }
return augmentedPages return augmentedPages
@ -174,7 +175,7 @@ const DYNAMIC_META_KEY = '__nuxt_dynamic_meta_key' as const
const pageContentsCache: Record<string, string> = {} const pageContentsCache: Record<string, string> = {}
const metaCache: Record<string, Partial<Record<keyof NuxtPage, any>>> = {} const metaCache: Record<string, Partial<Record<keyof NuxtPage, any>>> = {}
export async function getRouteMeta (contents: string, absolutePath: string): Promise<Partial<Record<keyof NuxtPage, any>>> { export async function getRouteMeta (contents: string, absolutePath: string, esbuildOptions?: TransformOptions): Promise<Partial<Record<keyof NuxtPage, any>>> {
// set/update pageContentsCache, invalidate metaCache on cache mismatch // set/update pageContentsCache, invalidate metaCache on cache mismatch
if (!(absolutePath in pageContentsCache) || pageContentsCache[absolutePath] !== contents) { if (!(absolutePath in pageContentsCache) || pageContentsCache[absolutePath] !== contents) {
pageContentsCache[absolutePath] = contents pageContentsCache[absolutePath] = contents
@ -194,7 +195,7 @@ export async function getRouteMeta (contents: string, absolutePath: string): Pro
return {} return {}
} }
const js = await transform(script.code, { loader: script.loader }) const js = await transform(script.code, { loader: script.loader, ...esbuildOptions })
const ast = parse(js.code, { const ast = parse(js.code, {
sourceType: 'module', sourceType: 'module',
ecmaVersion: 'latest', ecmaVersion: 'latest',