Adding bundle analyzer to Sanity build command to optimize bundle size
Yes, you can add a bundle analyzer to your Sanity Studio build by customizing the Vite configuration in your sanity.cli.ts (or sanity.cli.js) file. Since Sanity Studio v3 uses Vite as its build tool, you can extend the default Vite configuration with plugins like rollup-plugin-visualizer.
Adding a Bundle Analyzer
Here's how to configure it:
1. Install the visualizer plugin:
npm install --save-dev rollup-plugin-visualizer2. Configure sanity.cli.ts:
Create or update your sanity.cli.ts file at the root of your project:
import {defineCliConfig} from 'sanity/cli'
import {visualizer} from 'rollup-plugin-visualizer'
export default defineCliConfig({
api: {
projectId: 'your-project-id',
dataset: 'your-dataset'
},
vite: (config) => {
// Only add visualizer in production builds
if (process.env.NODE_ENV === 'production') {
config.plugins?.push(
visualizer({
filename: './dist/stats.html',
open: true,
gzipSize: true,
brotliSize: true,
})
)
}
return config
}
})3. Build your Studio:
sanity buildThis will generate a stats.html file in your dist folder showing your bundle composition.
Reducing Bundle Size
With a 39MB unminified / 15MB minified bundle, here are some strategies to reduce it:
Conditionally include heavy plugins: If you're using plugins like @sanity/vision (the GROQ playground), consider only including them in development:
import {defineConfig} from 'sanity'
import {structureTool} from 'sanity/structure'
import {visionTool} from '@sanity/vision'
export default defineConfig({
// ... other config
plugins: [
structureTool(),
// Only include vision in development
...(process.env.NODE_ENV === 'development' ? [visionTool()] : [])
]
})Code splitting: Vite automatically handles code splitting, but you can optimize further by lazy-loading custom components and heavy dependencies.
Analyze dependencies: Use the visualizer to identify which packages are contributing most to your bundle size. Consider alternatives or lazy-loading strategies for the largest ones.
The vite configuration property in sanity.cli.ts exposes the default Vite config and automatically merges your customizations, making it straightforward to add build analysis tools like rollup-plugin-visualizer.
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.