DEV Community

Mark
Mark

Posted on

6

Vite - Code Splitting Strategy

The Problem Solved by Code Splitting

Firstly, let's look at the problems with the traditional single chunk packaging mode:

  1. Can not import on demand

All the code is bundled into one chunk, which means that the code needed for page initialization and the code for the route components are all bundled together.

  1. Can not use network cache

Normally, the name of a chunk is generated based on the hash value of the file content. Therefore, every time the code is modified, the name of the chunk changes, which prevents the browser from using the local cache.

Code splitting is aimed at resolving these issues to enhance page load performance.

Vite's Default Chunk Splitting Strategy

Before version 2.9

  • One chunk corresponds to one CSS file.
  • Logic code will be packaged into one chunk.
  • Third-party dependencies are packaged into one chunk.

After version 2.9

The changed place is that both the third-party packages and the business code are now in one chunk.

If you want to control the code splitting strategy with a finer granularity, you need to use the manualChunks configuration. The config is approximately as follows:

export default defineConfig({
  build: {
    rollupOptions: {
      output: {
        /**
         * 1. Use in object form
         * Package the lodash module into a chunk, named lodash
         */
         manualChunks: {
           lodash: ['lodash'],
         },

        /**
         * 2. Use in function form
         * Package all third-party packages into one chunk, named vendor
         */
        manualChunks(id, { getModuleInfo, getModuleIds }) {
          if (id.includes('node_modules')) {
            return 'vendor';
          }
        },
      },
    },
  },
});
Enter fullscreen mode Exit fullscreen mode

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more