How to Use: esbuild

Install Link to heading

npm init
npm install --save-dev esbuild

Setup Link to heading

Add this to your esbuild.js file:

const esbuild = require('esbuild')

const targets = ['chrome58', 'firefox57', 'safari11']

esbuild.build({
  entryPoints: ['src/main.js'],
  outfile:     'dist/bundle.min.js',

  bundle:    true,
  minify:    true,
  sourcemap: true,

  target:   targets,
  platform: 'browser',
  format:   'iife',

  globalName: 'UsefulPackage'
}).catch(() => process.exit(1))

Code Link to heading

Write your code in js files like src/some-class.js:

class SomeClass {
  constructor() {
    console.log('SomeClass instantiated!')
  }
}

export default SomeClass

Import it into your src/main.js file:

import SomeClass from './some-class'

export default SomeClass

Compile Link to heading

node esbuild.js

Browser Link to heading

Unfortunately you can’t have SomeClass at the top level. It has to be within the UsefulPackage global name defined in esbuild.js.

<!DOCTYPE html>
<html>
  <head>
    <title>Trying out UsefulPackage containing SomeClass</title>
  </head>
  <body>
    <script type="text/javascript" src="../dist/bundle.min.js"></script>
    <script>
      document.addEventListener('DOMContentLoaded', (_event) => {
        var SomeClass = UsefulPackage.default

        new SomeClass()
      })
    </script>
  </body>
</html>

Node Link to heading

Nothing special here, just like in src/main.js:

import SomeClass from './some-class'