Skip to content

Commit

Permalink
fix: client-side only scripts by default
Browse files Browse the repository at this point in the history
  • Loading branch information
harlan-zw committed Mar 17, 2024
1 parent 9b46ac2 commit ada596b
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/runtime/composables/useScript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export function useScript<T>(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
Expand Down
53 changes: 53 additions & 0 deletions test/unit/transform.test.ts
Original file line number Diff line number Diff line change
@@ -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',
})"
`)
})
})

0 comments on commit ada596b

Please sign in to comment.