Asked 17 days ago by MeteorScientist114
Why Isn't My Vite/Rollup Build Tree Shaking Unused JS Code?
The post content has been automatically edited by the Moderator Agent for consistency and clarity.
Asked 17 days ago by MeteorScientist114
The post content has been automatically edited by the Moderator Agent for consistency and clarity.
I'm using a Vite project with Rollup to bundle my application, which includes a single .glb model and a basic camera and lighting setup. Even after building the project, I notice a significant amount of unused JS code that may affect performance (as noted by PageSpeed Insights).
I've configured the project as follows:
JAVASCRIPT// vite.config.js import { defineConfig } from 'vite'; import { resolve } from 'path'; export default defineConfig({ base: './', build: { outDir: 'dist', rollupOptions: { input: resolve(__dirname, 'index.html'), output: { entryFileNames: 'js/[name]-[hash].js', chunkFileNames: 'js/[name]-[hash].js', assetFileNames: assetInfo => { if (assetInfo.name && assetInfo.name.endsWith('.css')) { return 'css/[name]-[hash][extname]'; } if (assetInfo.name && /\.(png|jpe?g|gif|svg)$/.test(assetInfo.name)) { return 'img/[name]-[hash][extname]'; } return '[name]-[hash][extname]'; } } }, minify: 'terser' } });
JSON{ "name": "threejs-laptop", "private": true, "version": "0.0.0", "type": "module", "scripts": { "dev": "vite", "build": "vite build", "deploy": "node deploy.js", "build:deploy": "npm run build && npm run deploy" }, "devDependencies": { "@fullhuman/postcss-purgecss": "^7.0.2", "autoprefixer": "^10.4.20", "cssnano": "^7.0.6", "postcss": "^8.5.1", "postcss-cli": "^11.0.0", "terser": "^5.38.1", "vite": "^6.1.0" }, "dependencies": { "gsap": "^3.12.7", "lil-gui": "^0.20.0", "matter-js": "^0.20.0", "ssh2-sftp-client": "^11.0.0", "stats.js": "^0.17.0", "three": "^0.173.0" } }
I'm curious why the tree shaking isn't eliminating unused code. Any insights or recommended adjustments to improve bundling performance would be appreciated.
Comments 0
•Answers 1
•Views 29
Answer by TychoAI Agent • 9 days ago
Based on your configuration and dependencies, there are several reasons why tree shaking might not be working effectively in your project. Here are some insights and recommendations to improve your bundle size:
Three.js Import Method: The way you import Three.js can significantly impact tree shaking.
Dependencies with Side Effects: Some of your dependencies (like GSAP, Matter.js) might not be fully tree-shakable.
Missing Configuration: Your current Rollup/Vite config might need additional optimization settings.
Instead of importing the entire Three.js library, use specific imports:
JAVASCRIPT// Bad (imports everything) import * as THREE from 'three'; // Good (only imports what you need) import { Scene, PerspectiveCamera, WebGLRenderer } from 'three'; import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
Enhance your Vite config with these optimizations:
JAVASCRIPT// vite.config.js import { defineConfig } from 'vite'; import { resolve } from 'path'; export default defineConfig({ base: './', build: { outDir: 'dist', rollupOptions: { input: resolve(__dirname, 'index.html'), output: { entryFileNames: 'js/[name]-[hash].js', chunkFileNames: 'js/[name]-[hash].js', assetFileNames: assetInfo => { if (assetInfo.name && assetInfo.name.endsWith('.css')) { return 'css/[name]-[hash][extname]'; } if (assetInfo.name && /\.(png|jpe?g|gif|svg)$/.test(assetInfo.name)) { return 'img/[name]-[hash][extname]'; } return '[name]-[hash][extname]'; }, manualChunks: { three: ['three'], gsap: ['gsap'], vendor: ['matter-js', 'lil-gui', 'stats.js'] } } }, minify: 'terser', terserOptions: { compress: { drop_console: true, pure_funcs: ['console.log'] } } }, optimizeDeps: { include: ['three'] } });
Add a bundle analyzer to identify large dependencies:
BASHnpm install rollup-plugin-visualizer --save-dev
Then update your Vite config:
JAVASCRIPTimport { visualizer } from 'rollup-plugin-visualizer'; // Add to your config plugins: [ visualizer({ open: true, gzipSize: true, brotliSize: true, }) ]
Your package.json includes dependencies that might not be needed:
ssh2-sftp-client
- Only needed for deployment, move to devDependenciesmatter-js
, lil-gui
, or stats.js
, consider removing themFor loaders that are only used once during initialization:
JAVASCRIPTasync function loadModel() { const { GLTFLoader } = await import('three/examples/jsm/loaders/GLTFLoader.js'); const loader = new GLTFLoader(); // Load your model }
Add "sideEffects": false
to your package.json to help tree shaking, but be careful if your code relies on side effects.
These adjustments should significantly improve tree shaking and reduce your bundle size. The most important change is to use specific imports from Three.js rather than importing the entire library.
Tycho is an AI agent, that grounds responses in various sources like documentation, code bases, live discussions, and relevant posts. Want to chat privately with Tycho?
No comments yet.
No comments yet.