Skip to content

johnie/esbuild-coffeescript

Repository files navigation

esbuild-coffeescript

esbuild-coffeescript npm version Downloads

This plugin lets you import CoffeeScript files when bundling with Esbuild

Transform and bundle .coffee and .litcoffee files seamlessly with esbuild's lightning-fast build system.

Table of Contents

Installation

# npm
npm install --save-dev esbuild-coffeescript esbuild

# pnpm
pnpm add --dev esbuild-coffeescript esbuild

Compatibility

This plugin is tested against Node.js versions 20.x, 22.x, and 24.x.

Quick Start

Basic CoffeeScript File

Create a CoffeeScript file:

main.coffee

answer = 42
console.log("the answer is #{answer}")

Build Configuration

build.js

import coffeeScriptPlugin from "esbuild-coffeescript";
import esbuild from "esbuild";

esbuild
  .build({
    entryPoints: ["main.coffee"],
    bundle: true,
    outfile: "out.js",
    plugins: [coffeeScriptPlugin()],
  })
  .catch(() => process.exit(1));

Generated Output

The above CoffeeScript compiles to:

(function () {
  var answer;
  answer = 42;
  return console.log("the answer is " + answer);
}).call(this);

Usage Examples

Literate CoffeeScript

The plugin automatically detects and processes .litcoffee files:

docs.litcoffee

# My Application

This is documentation written in Markdown with embedded CoffeeScript:

    class Calculator
      add: (a, b) -> a + b
      multiply: (a, b) -> a * b

    calc = new Calculator()
    console.log calc.add(5, 3)

build.js

esbuild.build({
  entryPoints: ["docs.litcoffee"],
  bundle: true,
  plugins: [coffeeScriptPlugin({ literate: true })],
  outfile: "calculator.js",
});

Multiple File Project

models/User.coffee

class User
  constructor: (@name, @email) ->

  greet: -> "Hello, I'm #{@name}"

module.exports = { User }

main.coffee

{User} = require('./models/User.coffee')

user = new User('John', '[email protected]')
console.log user.greet()

build.js

esbuild.build({
  entryPoints: ["main.coffee"],
  bundle: true,
  plugins: [coffeeScriptPlugin({ bare: true })],
  outfile: "app.js",
  format: "esm",
});

Web Application Bundle

import coffeeScriptPlugin from "esbuild-coffeescript";

esbuild.build({
  entryPoints: ["src/app.coffee"],
  bundle: true,
  outdir: "dist",
  plugins: [coffeeScriptPlugin()],
  format: "esm",
  target: "es2020",
  minify: true,
  sourcemap: true,
});

Configuration Options

Pass configuration options to the plugin constructor:

coffeeScriptPlugin({
  bare: true,
  inlineMap: true,
  // ... other options
});

Available Options

Option Type Default Description
inlineMap boolean false Output source map as base64-encoded string in comment
filename string auto-detected Filename for source map (can include path)
bare boolean false Output without top-level function safety wrapper
header boolean false Output "Generated by CoffeeScript" header
transpile object undefined Babel transpilation options (see CoffeeScript docs)
ast boolean false Return abstract syntax tree instead of compiled code
literate boolean auto-detected Parse as Literate CoffeeScript

Configuration Examples

Development Build with Source Maps

coffeeScriptPlugin({
  inlineMap: true,
  bare: true,
  header: true,
});

Production Build (Bare Output)

coffeeScriptPlugin({
  bare: true,
  header: false,
});

Modern JavaScript Transpilation

coffeeScriptPlugin({
  bare: true,
  transpile: {
    presets: ["@babel/preset-env"],
    targets: { node: "18" },
  },
});

Advanced Usage

TypeScript Integration

Use alongside esbuild's built-in TypeScript support:

esbuild.build({
  entryPoints: ["src/main.ts", "src/utils.coffee"],
  bundle: true,
  plugins: [coffeeScriptPlugin({ bare: true })],
  outdir: "dist",
  format: "esm",
});

Watch Mode

const context = await esbuild.context({
  entryPoints: ["src/app.coffee"],
  bundle: true,
  plugins: [coffeeScriptPlugin()],
  outdir: "dist",
});

await context.watch();
console.log("Watching for changes...");

Custom File Extensions

While not directly configurable, you can pre-process files with custom extensions:

// For .cjsx or other extensions, rename or copy files first
import { copyFile } from "fs/promises";

await copyFile("src/component.cjsx", "src/component.coffee");

esbuild.build({
  entryPoints: ["src/component.coffee"],
  plugins: [coffeeScriptPlugin()],
  // ...
});

Error Handling

The plugin provides detailed error reporting with location information:

invalid.coffee

hello . 8  # Syntax error

Error Output:

✘ [ERROR] unexpected .

    invalid.coffee:1:6:
      1 │ hello . 8
        ╵       ^

Handling Build Errors in Code

try {
  await esbuild.build({
    entryPoints: ["main.coffee"],
    plugins: [coffeeScriptPlugin()],
    logLevel: "silent", // Suppress esbuild's error output
  });
} catch (error) {
  console.error("Build failed:", error.message);
  // Custom error handling logic
}

Migration Guide

From v2.x to v3.x

  • Breaking Change: Now requires Node.js 20+
  • New: ESM-first approach
  • Updated: Latest CoffeeScript compiler (2.7.0)
  • Updated: esbuild peer dependency to ^0.25.9

Before (v2.x):

const coffeeScriptPlugin = require("esbuild-coffeescript");

After (v3.x):

import coffeeScriptPlugin from "esbuild-coffeescript";

Troubleshooting

Common Issues

"Cannot resolve CoffeeScript file"

✘ [ERROR] Could not resolve "./utils.coffee"

Solution: Ensure the file exists and the path is correct. esbuild resolves paths relative to the importing file.

"Unexpected token" in generated code

This usually indicates a CoffeeScript compilation error.

Solution: Check your CoffeeScript syntax. Use bare: true to remove the function wrapper if needed.

Source maps not working

Solution: Use inlineMap: true option or configure esbuild's sourcemap option:

esbuild.build({
  sourcemap: true, // or 'inline'
  plugins: [coffeeScriptPlugin({ inlineMap: true })],
  // ...
});

Performance Tips

  1. Use bare: true for smaller output when the function wrapper isn't needed
  2. Enable minification in production builds
  3. Use bundle: true to reduce the number of HTTP requests
  4. Consider code splitting for large applications

Getting Help

Why CoffeeScript?

While some consider CoffeeScript a thing of the past, it remains actively maintained and widely used:

  • 1.6+ million weekly downloads on npm
  • Concise, readable syntax that compiles to clean JavaScript
  • Excellent for rapid prototyping and functional programming patterns
  • Mature ecosystem with extensive tooling support

This plugin provides an excellent migration path for CoffeeScript projects wanting to leverage esbuild's speed and modern bundling features.

Contributing

We welcome contributions! Please see our Contributing Guide for details.

Development Setup

# Clone the repository
git clone https://github.com/johnie/esbuild-coffeescript.git
cd esbuild-coffeescript

# Install dependencies
pnpm install

# Run tests
pnpm test

# Build the project
pnpm build

Running Tests

# Run all tests
pnpm test

# Watch mode
pnpm test:watch

# Coverage report
pnpm test:coverage

License

MIT © Johnie Hjelm


Tip: ⭐ Star this repo if you find it helpful!

About

This plugin lets you import CoffeeScript files when bundling with Esbuild

Resources

Stars

Watchers

Forks

Contributors 4

  •  
  •  
  •  
  •