pimski's avatar
Level 13

How can I force vite/rollup to include partials in a page chunck?

Suppose you have the following directory structure (from laravel breeze):

/resources/js/Pages/Profile/Edit.vue
/resources/js/Pages/Profile/Partials/DeleteUser.vue
/resources/js/Pages/Profile/Partials/UpdateUser.vue

When you run npm run build it will generate chuncks of js files, which is good. However, I would like to see a single file for profile edit, with the partials included, since they're not used anywhere else. Is this possible in rollup?

0 likes
2 replies
LaryAI's avatar
Level 58

To bundle your partials into a single chunk for the profile edit page, you can use Vite's dynamic import feature to import your partials directly into your Edit.vue component. This will hint to Vite that these components are only used by Edit.vue and should be included in the same chunk.

Here's how you can modify your Edit.vue component to dynamically import the partials:

<template>
  <!-- Your template code -->
</template>

<script>
// Dynamically import your partials
const DeleteUser = () => import('./Partials/DeleteUser.vue');
const UpdateUser = () => import('./Partials/UpdateUser.vue');

export default {
  components: {
    DeleteUser,
    UpdateUser
  },
  // rest of your component logic
}
</script>

<style>
/* Your styles */
</style>

By using dynamic imports, Vite will create a single chunk for Edit.vue that includes both DeleteUser.vue and UpdateUser.vue. This is because dynamic imports are treated as points to split code, but since you're importing them directly in Edit.vue, Vite understands that they should be part of the same chunk.

If you still find that Vite is creating separate chunks for these components, you can further customize the chunking behavior by modifying the vite.config.js file. You can use the manualChunks option in the Rollup options to explicitly tell Vite how to split the code:

// vite.config.js
export default {
  // ... other Vite config options
  build: {
    rollupOptions: {
      output: {
        manualChunks(id) {
          if (id.includes('path-to-your-partials')) {
            // Return the same name for all partials to bundle them into one chunk
            return 'edit-profile-chunk';
          }
        }
      }
    }
  }
}

Replace 'path-to-your-partials' with the actual path to your partials. This configuration tells Rollup to put any module that matches the path into the same chunk named 'edit-profile-chunk'.

Remember to run npm run build after making these changes to see the effect on the generated chunks.

pimski's avatar
Level 13

Not bad Lary! First tip (dynamic imports) doesn't do anything. However, second tip does result in a single chunck. Down side: this requires you to create an if-condition in vite.config.js for each page where you want to do this. I was hoping for a strategy inside the Edit.vue component...

Please or to participate in this conversation.