stephenS
Denoβ€’3y ago
stephen

How do people bundle their Deno code for web?

I am currently using Deno bundle command to bundle my code for web. Is there a better alternative for bundling + type-checking folks are using? I can't find anything that looks robust and Deno-ish and ended up with a big hacky script (below). I love esbuild but it doesn't support type-checking and esbuild_deno_loader is still maturing.

import * as esbuild from 'https://deno.land/x/esbuild@v0.17.11/mod.js'
import { denoPlugin } from 'https://deno.land/x/esbuild_deno_loader@0.6.0/mod.ts'

const input: string = Deno.args[0]
const output: string = Deno.args[1]
const importMap: string | undefined = Deno.args[2]?.replace(/^--imports=/, '')
const watchDir: string | undefined = Deno.args[3]?.replace(/^--watch=/, '')

const options: esbuild.BuildOptions = {
  sourcemap: 'linked',
  bundle: true,
  entryPoints: [input],
  format: 'esm',
  logLevel: `warning`,
  outfile: output,
  treeShaking: true,
  minify: true,
  banner: {
    // Live-reload.
    ...(watchDir != null &&
      {
        'js':
          'new EventSource(\'/esbuild\').onchange = () => location.reload()',
      }),
  },
  plugins: [
    // Hack around JSON loader overrides in esbuild_deno_loader that flag type
    // assertions.
    {
      name: 'json',
      setup: (build) =>
        build.onLoad({ filter: /\.json$/ }, () => ({ loader: 'json' })),
    },
    denoPlugin({
      ...(importMap != null && { importMapURL: new URL(importMap) }),
    }) as unknown as esbuild.Plugin,
  ],
}

if (watchDir != null) {
  const ctx = await esbuild.context(options)
  await Promise.all([ctx.watch(), ctx.serve({ servedir: watchDir })])
} else {
  await esbuild.build(options)
  esbuild.stop()
}
Was this page helpful?