Removing Console Output in Production Builds with Vite and Terser
Easily Remove All Console Output After Build: Give Your Code a 'Mute' Opportunity!
Have you ever felt embarrassed about leaving a bunch of debug console statements in your production application? Worry no more! I'll show you how to remove all console output by configuring Vite's build process.
Step 1: Install the Plugin
We need a plugin called rollup-plugin-terser to minify and mangle our code while stripping console statements. Open your terminal and run:
npm install rollup-plugin-terser --save-dev
Step 2: Configure Vite
Now we need to modify the Vite configuration file (typically vite.config.js) to use the terser plugin. Update the file as shown below:
import { defineConfig } from 'vite';
import { terser } from 'rollup-plugin-terser';
export default defineConfig({
// ... other configurations
build: {
rollupOptions: {
plugins: [
terser({
compress: {
drop_console: true, // Remove all console statements
},
}),
],
},
},
});
Step 3: Build and Enjoy Silence
Now run your Vite build command and let the magic happen:
npm run build
That's it! Your code is now minified, mangled, and all console output is gone. Your application will be cleaner in production and won't leak any secrets.
Bonus: Mute Console Entirely
If you want to silence all console methods dircetly in your code, you can add this snippet to your entry file:
console.log = () => {};
console.warn = () => {};
console.error = () => {};
console.debug = () => {};
console.info = () => {};
This will override the default console functions, keeping your console quiet.