Nuxt Config Setup
The simplest way to load NPM globally in your Nuxt App is to use Nuxt config. Alternatively you can directly use the useScriptNpm composable.
export default defineNuxtConfig({
scripts: {
registry: {
npm: {
packageName: 'lodash'
}
}
}
})useScriptNpm()
The useScriptNpm composable lets you have fine-grain control over when and how NPM is loaded on your site.
const { proxy } = useScriptNpm()
// loads package from CDNPlease follow the Registry Scripts guide to learn more about advanced usage.
Example
Using NPM only in production while using the proxy to send events.
<script setup lang="ts">
const { proxy } = useScriptNpm()
// noop in development, ssr
// just works in production, client
function handleAction() {
// loads package from CDN
}
</script>
<template>
<div>
<button @click="handleAction">
Send Event
</button>
</div>
</template>Background
When working with npm files, you'd typically include them as a node_module dependency in the package.json file. However,
optimizing the script loading of these scripts can be difficult, requiring a dynamic import of the module from a separate chunk and
loading it only when needed. It also slows down your build as the module needs to be transpiled.
The useScriptNpm() registry script abstracts this process, allowing you to load scripts that export immediately invokable functions with a single line of code.
In many instances it will still make more sense to include the script as a dependency in the package.json file, but for scripts that are not used often or
are not critical to the application, this can be a great alternative.
To begin with we can think of using this script as an alternative to the useHead composable. You can see an example of the abstraction
layers in the following code sample.
useScriptNpm({
packageName: 'js-confetti',
file: 'dist/js-confetti.browser.js',
version: '0.12.0',
})
useScript('https://cdn.jsdelivr.net/npm/[email protected]/dist/js-confetti.browser.js')
useHead({
script: [
{ src: 'https://cdn.jsdelivr.net/npm/js-confetti@latest/dist/js-confetti.browser.js' }
]
})
useScriptNpm()
The useScriptNpm() composable lets you have fine-grain control over when and how npm scripts load on your site.
function useScriptNpm<T extends Record<string | symbol, any>>(_options: NpmInput) {}
Please follow the Registry Scripts guide to learn more about advanced usage.
Return
To get types for the script you're loading, you'll need to augment the types of the useScriptNpm() function.
interface SomeApi {
doSomething: () => void
}
useScriptNpm<SomeApi>({
packageName: 'some-api'
})
packageNamestring required The npm package name to load.
filestringThe specific file path within the package to load.
versionstring = 'latest'The package version to load.
provider'jsdelivr' | 'cdnjs' | 'unpkg' = 'unpkg'The CDN provider to use for loading the package.
Example
See the Tutorial: Load js-confetti for further examples.