You're viewing the Inertia.js v2.0 pre-release documentation. Upgrade guide →
Code splitting breaks apart the various pages of your application into smaller bundles, which are then loaded on demand when visiting new pages. This can significantly reduce the size of the initial JavaScript bundle loaded by the browser, improving the time to first render.
While code splitting is helpful for very large projects, it does require extra requests when visiting new pages. Generally speaking, if you're able to use a single bundle, your app is going to feel snappier.
To enable code splitting you'll need to tweak the resolve
callback in your createInertiaApp()
configuration, and how you do this is different depending on which bundler you're using.
Vite enables code splitting (or lazy-loading as they call it) by default when using their import.meta.glob()
function, so simply omit the { eager: true }
option, or set it to false
, to disable eager loading.
resolve: name => {
- const pages = import.meta.glob('./Pages/**/*.vue', { eager: true })
- return pages[`./Pages/${name}.vue`]
+ const pages = import.meta.glob('./Pages/**/*.vue')
+ return pages[`./Pages/${name}.vue`]()
},
To use code splitting with Webpack, you will first need to enable dynamic imports via a Babel plugin. Let's install it now.
npm install @babel/plugin-syntax-dynamic-import
Next, create a .babelrc
file in your project with the following configuration:
{
"plugins": ["@babel/plugin-syntax-dynamic-import"]
}
Finally, update the resolve
callback in your app's initialization code to use import
instead of require
.
- resolve: name => require(`./Pages/${name}`),
+ resolve: name => import(`./Pages/${name}`),
You should also consider using cache busting to force browsers to load the latest version of your assets. To accomplish this, add the following configuration to your webpack configuration file.
output: {
chunkFilename: 'js/[name].js?id=[chunkhash]',
}