From ada596b89dc5e6abc976a4824ab0e7d6bc522a7b Mon Sep 17 00:00:00 2001 From: harlan Date: Sun, 17 Mar 2024 20:40:30 +1100 Subject: [PATCH] fix: client-side only scripts by default --- src/runtime/composables/useScript.ts | 1 + test/unit/transform.test.ts | 53 ++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 test/unit/transform.test.ts diff --git a/src/runtime/composables/useScript.ts b/src/runtime/composables/useScript.ts index 56a1b572..f2f27963 100644 --- a/src/runtime/composables/useScript.ts +++ b/src/runtime/composables/useScript.ts @@ -12,6 +12,7 @@ export function useScript(input: NuxtUseScriptInput, options?: NuxtUseScriptO await nuxtApp.hooks.callHook('scripts:transform', { script, options }) return script }, + mode: 'client', // default mode is client-only, loaded as we hydrate ...options, }) // used for devtools integration diff --git a/test/unit/transform.test.ts b/test/unit/transform.test.ts new file mode 100644 index 00000000..b785f21f --- /dev/null +++ b/test/unit/transform.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, it } from 'vitest' +import { parse } from 'acorn-loose' +import { parseURL } from 'ufo' +import type { ScriptInjectOptions } from '../../src/plugins/transform' +import { NuxtScriptTransformer } from '../../src/plugins/transform' + +async function transform(code: string | string[], options: ScriptInjectOptions) { + const plugin = NuxtScriptTransformer.vite(options) as any + const res = await plugin.transform.call( + { parse: (code: string) => parse(code, { ecmaVersion: 2022, sourceType: 'module', allowImportExportEverywhere: true, allowAwaitOutsideFunction: true }) }, + Array.isArray(code) ? code.join('\n') : code, + 'file.js', + ) + return res?.code +} + +describe('nuxtScriptTransformer', () => { + it('string arg', async () => { + const code = await transform( + `const instance = useScript('https://static.cloudflareinsights.com/beacon.min.js', { + assetStrategy: 'bundle', + })`, + { + resolveScript(src) { + return `/_scripts${parseURL(src).pathname}` + }, + }, + ) + expect(code).toMatchInlineSnapshot(` + "const instance = useScript('/_scripts/beacon.min.js', { + assetStrategy: 'bundle', + })" + `) + }) + + it('options arg', async () => { + const code = await transform( + `const instance = useScript({ defer: true, src: 'https://static.cloudflareinsights.com/beacon.min.js' }, { + assetStrategy: 'bundle', + })`, + { + resolveScript(src) { + return `/_scripts${parseURL(src).pathname}` + }, + }, + ) + expect(code).toMatchInlineSnapshot(` + "const instance = useScript({ defer: true, src: '/_scripts/beacon.min.js' }, { + assetStrategy: 'bundle', + })" + `) + }) +})