How to Use: esbuild

Install

npm init
npm install --save-dev esbuild

Setup

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

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

node esbuild.js

Browser

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

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

import SomeClass from './some-class'