The modern property in Nuxt.js allows you to serve both modern bundles to modern browsers and legacy bundles to those legacy browsers that still exist. When we write modern JavaScript code using async/await, fetch, arrow functions etc we still transpile this code to ES5 and bundle it with polyfills to accommodate the small percentage of users still on older browsers.
The solution is to use
<script type="module"> // for modern browsers
<script nomodule> // for legacy ones
Nuxt.js allows us to easily activate this by using the modern property. By default it is set to false so if you want to use it you will have to add it to your package.json script.
There are 3 possible values for the modern mode, 'client', 'server' and false.
- 'client': Serves both the modern bundle and the legacy bundle scripts. It will provide a link rel="modulepreload" for the modern bundle.
- 'server' or true: The node.js server will check the browser version based on the user agent and serve the corresponding modern or legacy bundle.
- false: Disables the modern build
In order to active it you will need to add the --modern flag(-m for short) and add the mode you require to your build or start scripts.
{
"scripts": {
"build: "nuxt build --modern=server",
}
}
When building static sites which use the generate command the modern property also works but only the client option is honoured and will be selected automatically so we don't have to provide any values.
{
"scripts": {
"generate: "nuxt generate -m",
}
}
And that's it. Just by modifying one small command you will now reduce your bundle size for modern browsers yet still have a fallback for those legacy ones. :)