How to bundle multiple components into single module in Svelte?

1.1k views Asked by At

I have an application build using Svelte (v3), Routify (v2) and Vite (v3). Home page of application comprises of various sections and each section comprises of multiple components. Hence when this page loads, it makes network request to 50+ components resulting into network waterfall hell!

Is there any mechanism to bundle the components into modules (like feature modules) and load them instead? Example, I can bundle multiple header related components into one header-module and make 1 network request instead of many!

enter image description here

routify.config.js

module.exports = {
  routifyDir: '.routify',
  dynamicImports: true,
  extensions: ['svelte']
}

vite.config.js

export default defineConfig({
  server: {
    port: 5000,
  },
  plugins: [
    svelte({
      preprocess: [preprocess()],
    }),
  ],
});

Ref. to code in GitHub Repo

2

There are 2 answers

0
JakeDK On

Routify only handles loading your page and modules (_layout.svelte).

That means for the page /admin/dashboard, Routify will dynamically import

_layout.svelte
admin/_layout.svelte
admin/dashboard.svelte

How you import components is between you and your bundler. In this case Vite. It sounds like Vite is converting your imports to dynamic imports.

0
cascading-jox On

I believe your issue is a non-issue. I am quite certain you just forgot to build it for production.

Before I built your project, I was confused because vite is excellent at fixing what you are describing is the issue. When running vite in developlemnt mode, it is doing hot module replacement, updating the changed component in real time when it detects any change instead of the whole page. In order for vite to be able to do this, I assume it needs to load each component individually, hence the "waterfall hell".

If you instead build the website for production using npm run build:prod and then preview the site locally using npm run preview you can see that all the separate component requests are gone, and instead you have a couple optimized bundles.

In development mode, you have 67 requests for the home page: Development mode

When the website is built for production, you have 8 requests for the home page: Production mode