This short post shows a simple example of how to integrate the Closure compiler with Snowpack to create an optimized Svelte production build.

Snowpack

You can read more about Snowpack in the official documentation, but in summary, Snowpack is an incremental build tool that allows you to serve unbundled applications during development. Unlike Webpack and other traditional bundlers, Snowpack creates a dev environment where ESM modules are loaded directly by the browser as individual files. This is more efficient since you avoid potentially costly bundling operations that have to process the entire set of files in your application even for small code changes.

For a great introduction to Snowpack and the plans to integrate Snowpack with Svelte, I recommend watching this Svelte Summit video.

Production

Serving individual ESM modules in the browser is great for creating an efficient dev environment, but in most cases it still makes sense to do bundled builds for production. Luckily Snowpack offers a plugin system that makes it trivial to integrate your favorite bundler with Snowpack to create optimized production bundles.

In my case I decided to go with Closure compiler since Svelte has shown very promising signs of being very compatible with Closure by default. If you are new to the Closure compiler, I recommend reading my previous article for some more background.

Below I have included an example of what a Snowpack – Closure compiler plugin might look like:

module.exports = function (snowpackConfig, pluginOptions) { const ClosureCompiler = require('google-closure-compiler').compiler; const fs = require("fs"); return { name: 'closure-compiler', async optimize() { const closureCompiler = new ClosureCompiler({ js: [ './build/_dist_/**.js', './build/web_modules/**.js', './externs.js' ], compilation_level: 'ADVANCED', language_in: 'ECMASCRIPT_2020', language_out: 'ECMASCRIPT_2015', module_resolution: 'node', jscomp_off: 'checkVars', rewrite_polyfills: false, warning_level: 'QUIET', process_common_js_modules: true, entry_point: './build/_dist_/index.js' }); return new Promise((resolve, reject) => { closureCompiler.run((exitCode, stdOut, stdErr) => { if (stdErr) { console.error(`Exit code: ${exitCode}`, stdErr); reject(); } else { fs.writeFileSync(pluginOptions.output, stdOut); resolve(); } }); }); } }; };

Next, we have to include the plugin with the default plugins in snowpack.config.js like so:

plugins: [ '@snowpack/plugin-svelte', '@snowpack/plugin-dotenv', ['./plugins/closure-compiler.js', { "output": "build/bundle.min.js" }], [ '@snowpack/plugin-run-script', { cmd: 'svelte-check --output human', watch: '$1 --watch', output: 'stream' }, ], ]

That’s it!

I have added my sample project to Github in case you want to try it our yourself.