Skip to content

Commit

Permalink
fix: cache bundled scripts relative to nuxt root
Browse files Browse the repository at this point in the history
  • Loading branch information
harlan-zw committed Sep 16, 2024
1 parent 582d360 commit cc5e01b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 13 deletions.
16 changes: 10 additions & 6 deletions src/assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,20 @@ const renderedScript = new Map<string, {
const ONE_YEAR_IN_SECONDS = 60 * 60 * 24 * 365

// TODO: refactor to use nitro storage when it can be cached between builds
export const storage = createStorage({
driver: fsDriver({
base: 'node_modules/.cache/nuxt/scripts',
}),
})
export const bundleStorage = () => {
const nuxt = useNuxt()
return createStorage({
driver: fsDriver({
base: resolve(nuxt.options.rootDir, 'node_modules/.cache/nuxt/scripts'),
}),
})
}

// TODO: replace this with nuxt/assets when it is released
export function setupPublicAssetStrategy(options: ModuleOptions['assets'] = {}) {
const assetsBaseURL = options.prefix || '/_scripts'
const nuxt = useNuxt()
const storage = bundleStorage()

// Register font proxy URL for development
addDevServerHandler({
Expand All @@ -46,7 +50,7 @@ export function setupPublicAssetStrategy(options: ModuleOptions['assets'] = {})
if (!scriptDescriptor || scriptDescriptor instanceof Error)
throw createError({ statusCode: 404 })

const key = `data:scripts:${filename}`
const key = `bundle:${filename}`
// Use storage to cache the font data between requests
let res = await storage.getItemRaw(key)
if (!res) {
Expand Down
16 changes: 9 additions & 7 deletions src/plugins/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { join } from 'pathe'
import { colors } from 'consola/utils'
import { tryUseNuxt, useNuxt } from '@nuxt/kit'
import { logger } from '../logger'
import { storage } from '../assets'
import { bundleStorage } from '../assets'
import { isJS, isVue } from './util'
import type { RegistryScript } from '#nuxt-scripts'

Expand Down Expand Up @@ -55,12 +55,13 @@ async function downloadScript(opts: {
if (src === url || !filename) {
return
}
const storage = bundleStorage()
const scriptContent = renderedScript.get(src)
let res: Buffer | undefined = scriptContent instanceof Error ? undefined : scriptContent?.content
if (!res) {
// Use storage to cache the font data between builds
if (await storage.hasItem(`data:scripts:${filename}`)) {
const res = await storage.getItemRaw<Buffer>(`data:scripts:${filename}`)
if (await storage.hasItem(`bundle:${filename}`)) {
const res = await storage.getItemRaw<Buffer>(`bundle:${filename}`)
renderedScript.set(url, {
content: res!,
size: res!.length / 1024,
Expand All @@ -80,11 +81,12 @@ async function downloadScript(opts: {
encoding = r.headers.get('content-encoding')
const contentLength = r.headers.get('content-length')
size = contentLength ? Number(contentLength) / 1024 : 0

return r.arrayBuffer()
}).then(r => Buffer.from(r))

storage.setItemRaw(`data:scripts:${filename}`, res)
await storage.setItemRaw(`bundle:${filename}`, res)
size = size || res!.length / 1024
logger.info(`Downloading script ${colors.gray(`${src}${filename} (${size.toFixed(2)} kB ${encoding})`)}`)
renderedScript.set(url, {
content: res!,
size,
Expand All @@ -110,7 +112,7 @@ export function NuxtScriptBundleTransformer(options: AssetBundlerTransformerOpti
logger.debug('[bundle-script-transformer] No scripts to bundle...')
return
}
logger.info('[bundle-script-transformer] Bundling scripts...')
logger.debug('[bundle-script-transformer] Bundling scripts...')
// less aggressive cache clearing in dev
if (!nuxt.options.dev) {
await fsp.rm(cacheDir, { recursive: true, force: true })
Expand All @@ -121,7 +123,7 @@ export function NuxtScriptBundleTransformer(options: AssetBundlerTransformerOpti
if (content instanceof Error || !content.filename)
return
await fsp.writeFile(join(nuxt.options.buildDir, 'cache', 'scripts', content.filename), content.content)
logger.info(colors.gray(` ├─ ${url}${joinURL(content.src)} (${content.size.toFixed(2)} kB ${content.encoding})`))
logger.debug(colors.gray(` ├─ ${url}${joinURL(content.src)} (${content.size.toFixed(2)} kB ${content.encoding})`))
}))
})

Expand Down

0 comments on commit cc5e01b

Please sign in to comment.