Skip to content

Commit

Permalink
feat: useScriptNpm
Browse files Browse the repository at this point in the history
  • Loading branch information
harlan-zw committed Mar 31, 2024
1 parent eac5a0d commit cd1248e
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,10 @@ export default defineNuxtModule<ModuleOptions>({
name: 'useScriptSegment',
from: resolve('./runtime/registry/segment'),
},
{
name: 'useScriptNpm',
from: resolve('./runtime/registry/npm'),
},
].map((i: Import) => {
i.priority = -1
return i
Expand Down
26 changes: 26 additions & 0 deletions src/runtime/registry/npm.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { type Input, object, optional, string } from 'valibot'
import { withBase } from 'ufo'
import { useScript, validateScriptInputSchema } from '#imports'
import type { NuxtUseScriptOptions } from '#nuxt-scripts'

export const NpmOptions = object({
packageName: string(),
file: optional(string()),
version: optional(string()),
})

export function useScriptNpm<T>(options: Input<typeof NpmOptions>, _scriptOptions?: NuxtUseScriptOptions<T>) {
const scriptOptions: NuxtUseScriptOptions<T> = _scriptOptions || {}
scriptOptions.beforeInit = () => {
validateScriptInputSchema(NpmOptions, options)
}
// TODO support multiple providers? (e.g. jsdelivr, cdnjs, etc.) Only unpkg for now
return useScript<T>({
src: typeof options === 'string' ? options : withBase(options.file || '', `https://unpkg.com/${options?.packageName}@${options.version}`),
}, {
...scriptOptions,
use() {
return new window.JSConfetti()
},
})
}

0 comments on commit cd1248e

Please sign in to comment.