When you use scripts from other sites on your website, you rely on another server to load these scripts. This can slow down your site and raise concerns about safety and privacy.
By bundling these scripts, you can host them yourself, which helps avoid these issues and keeps your site running smoothly.
During the build process, your code is checked to find any instances of useScript
that need to be bundled.
When a script is identified for bundling, it's downloaded and saved as a public asset at /_scripts/[hash].js
. Here, [hash]
represents the hash of the script's URL.
Important points about bundling:
// GOOD - Static values allow for bundling
useScript('https://example.com/script.js', {
bundle: true
})
// BAD - Dynamic values prevent bundling
useScript(scriptSrc, {
bundle: canBundle
})
Scripts can be bundled individually or on a global scale using specific settings.
To decide if an individual script should be bundled, use the bundle
option.
// Opt-in to bundle this specific script
useScript('https://example.com/script.js', {
bundle: true,
})
Adjust the default behavior for all scripts using the Nuxt Config. This example sets all scripts to be bundled by default.
export default defineNuxtConfig({
scripts: {
defaultScriptOptions: {
bundle: true,
}
}
})
While many scripts can be bundled, there are exceptions you need to be aware of.
For instance, certain scripts:
Scripts from known registries are pre-configured to either allow or disallow bundling. For your own scripts, you'll need to decide whether bundling is appropriate on a case-by-case basis.
Use the assets
option in your configuration to customize how scripts are bundled, such as changing the output directory for the bundled scripts.
export default defineNuxtConfig({
scripts: {
assets: {
prefix: '/_custom-script-path/',
}
}
})
More configuration options will be available in future updates.