Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vite produces unreasonably small chunks #9565

Closed
7 tasks done
gajus opened this issue Aug 7, 2022 · 7 comments
Closed
7 tasks done

Vite produces unreasonably small chunks #9565

gajus opened this issue Aug 7, 2022 · 7 comments

Comments

@gajus
Copy link
Contributor

gajus commented Aug 7, 2022

Describe the bug

Vite produces unreasonably small chunks (90% of all chunks are under 1KB with a few 300KB+).

Here is the full build log:

https://gist.github.com/gajus/0149233592085181331dde7076fc50b1

This is example website:

https://contra.com/p/gkOQlbLq-validating-postgre-sql-results-and-inferring-query-static-types

This is out Vite configuration:

import path from 'path';
import { default as react } from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
import { default as ssr } from 'vite-plugin-ssr/plugin';

const { VITE_BASE_URL } = process.env;

export default defineConfig(({ ssrBuild }) => {
  let build;

  if (!ssrBuild) {
    build = {
      emptyOutDir: true,
      manifest: true,
      minify: true,
      polyfillModulePreload: false,
      rollupOptions: {
        output: {
          chunkFileNames: 'chunk-[name].[hash].js',
          entryFileNames: 'entry-[name].[hash].js',
          inlineDynamicImports: false,
          sourcemap: true,
        },
      },
      sourcemap: true,
    };
  }

  return {
    base: VITE_BASE_URL ?? '/static/',
    build,
    plugins: [
      react({
        babel: {
          plugins: [
            'babel-plugin-relay',
            [
              'babel-plugin-styled-components',
              {
                displayName: true,
                fileName: false,
                pure: true,
                ssr: true,
              },
            ],
          ],
        },
      }),
      ssr(),
    ],
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src/'),
      },
    },
  };
});

If you try to inspect this page using Google tools, it doesn't even load – presumably because of 200 JavaScript chunks that that page needs to load.

https://search.google.com/test/mobile-friendly/result?id=ULZhtOfQfp1Gxj2wYhyCUw

This appears to be a bug. How to reduce the number of chunks?

Reproduction

N/A

System Info

M/A

Used Package Manager

yarn

Logs

No response

Validations

@gajus
Copy link
Contributor Author

gajus commented Aug 7, 2022

For context, I am familiar with manualChunks, and tried configuring chunks into what logically makes sense, e.g.

manualChunks: (id: string) => {
  // Some IDs are not file paths, e.g.
  // 'virtual:vite-plugin-ssr:pageFiles:client:client-routing'
  if (!id.includes(__dirname)) {
    return undefined;
  }

  // Rollup ID starts with a weird zero-width character that I was not able
  // to remove using trim() or regex.
  const pathStartIndex = id.indexOf('/');

  // Rollup IDs might include search parameters, e.g.
  // 'node_modules/react/cjs/react.production.min.js?commonjs-exports'
  const filePath = path.relative(
    __dirname,
    id.slice(pathStartIndex).split('?')[0]
  );

  if (filePath.startsWith('src/components/Icons/')) {
    return 'icons';
  }

  if (filePath.startsWith('src/hooks/')) {
    return 'hooks';
  }

  if (filePath.startsWith('node_modules/')) {
    return 'vendor';
  }

  return undefined;
},

However, attempting to modify chunks produces an error runtime:

chunk-hooks.87dd4e61.js:1 Uncaught TypeError: Cannot read properties of undefined (reading 'exports')
    at chunk-hooks.87dd4e61.js:1:1449

@gajus
Copy link
Contributor Author

gajus commented Aug 7, 2022

The only thing that appears to work is:

manualChunks: () => {
  return 'everything';
},

but that is far from ideal.

@gajus
Copy link
Contributor Author

gajus commented Aug 7, 2022

Looks like putting everything into a single chunk does not work either because of side effects that some modules have.

Is there a vite / rollup I could use to guard against side-effects, perhaps by wrapping imports in function calls?

@bluwy
Copy link
Member

bluwy commented Aug 7, 2022

As far as I'm aware, Vite doesn't meddle with chunking, and resorts to Rollup's default behaviour since #6534 (Vite 2.8). You can check the chunk strategy docs to get back to that behaviour if it helps. But besides that I'm not sure how this bug can be fixed, we can't assert a default strategy that works for everyone, except Rollup's.

@gajus
Copy link
Contributor Author

gajus commented Aug 7, 2022

Hard to resolve this issue when Vite community points fingers at Rollup, and Rollup points fingers are Vite.

For context, related conversation:

rollup/rollup#4327 (comment)

@bluwy
Copy link
Member

bluwy commented Aug 7, 2022

I'm not pointing fingers at Rollup. I'm just showing that Vite doesn't mess with chunking that could cause the behaviour you see, that is to my knowledge, which I'm happy to be proven wrong otherwise. Perhaps there indeed is a bug in Vite or Rollup, but it's impossible to know since the only repro we have is your website.

@github-actions
Copy link

github-actions bot commented Aug 9, 2022

Hello @gajus. Please provide a minimal reproduction using a GitHub repository or StackBlitz. Issues marked with need reproduction will be closed if they have no activity within 3 days.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants