or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

browser.mdcli.mdcompilation.mdindex.mdparsing.mdregistration.mdrepl.mdutilities.md
tile.json

browser.mddocs/

Browser Support

Client-side CoffeeScript compilation and execution for web browsers with source map support, script tag integration, and XHR loading capabilities.

Browser Compilation

CoffeeScript provides browser-optimized compilation functions for client-side use.

Browser Eval Function

Browser-safe evaluation function that uses the global scope instead of inheriting the compiler's scope.

/**
 * Browser-optimized eval function using global scope
 * @param code - CoffeeScript source code to evaluate
 * @param options - Browser evaluation options
 * @returns Result of code evaluation
 */
function eval(code: string, options?: BrowserEvalOptions): any;

interface BrowserEvalOptions {
  /** Compile without wrapper function (default: true in browser) */
  bare?: boolean;
  /** Include source map inline */
  inlineMap?: boolean;
}

Usage Examples:

// In browser environment
const result = CoffeeScript.eval('2 + 3 * 4');
console.log(result); // 14

// Evaluate with options
const code = `
  square = (x) -> x * x
  numbers = [1, 2, 3, 4, 5]
  squares = (square num for num in numbers)
  squares
`;
const squares = CoffeeScript.eval(code, { bare: true });
console.log(squares); // [1, 4, 9, 16, 25]

Browser Run Function

Browser-safe execution function that runs compiled code in a clean function scope.

/**
 * Browser-optimized run function with function scope
 * @param code - CoffeeScript source code to run
 * @param options - Browser run options
 * @returns Result of code execution
 */
function run(code: string, options?: BrowserRunOptions): any;

interface BrowserRunOptions {
  /** Compile without wrapper function (default: true) */
  bare?: boolean;
  /** Shift line numbers for stack traces */
  shiftLine?: boolean;
}

Usage Examples:

// Run CoffeeScript in browser
CoffeeScript.run(`
  console.log 'Hello from browser CoffeeScript!'
  
  class Calculator
    add: (a, b) -> a + b
    multiply: (a, b) -> a * b
  
  calc = new Calculator()
  console.log calc.add 5, 3
  console.log calc.multiply 4, 7
`);

Browser Compile Function

Enhanced compile function with automatic inline source map support for browsers.

/**
 * Browser-optimized compile function with inline source maps
 * @param code - CoffeeScript source code to compile
 * @param options - Browser compilation options
 * @returns Compiled JavaScript with inline source map
 */
function compile(code: string, options?: BrowserCompileOptions): string;

interface BrowserCompileOptions {
  /** Include source map inline (default: true in browser) */
  inlineMap?: boolean;
  /** Source filename for debugging */
  filename?: string;
}

Script Tag Integration

CoffeeScript supports <script type="text/coffeescript"> tags for inline browser compilation.

Inline CoffeeScript Scripts

<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/coffeescript@2.7.0/lib/coffeescript-browser-compiler-modern/coffeescript.js"></script>
</head>
<body>
  <script type="text/coffeescript">
    # Inline CoffeeScript code
    square = (x) -> x * x
    console.log "5 squared is #{square 5}"
    
    # DOM manipulation
    document.addEventListener 'DOMContentLoaded', ->
      button = document.createElement 'button'
      button.textContent = 'Click me!'
      button.onclick = -> alert 'Hello from CoffeeScript!'
      document.body.appendChild button
  </script>
</body>
</html>

External CoffeeScript Files

<!DOCTYPE html>
<html>
<head>
  <script src="coffeescript.js"></script>
</head>
<body>
  <script type="text/coffeescript" src="app.coffee"></script>
  <script type="text/coffeescript" src="utils.coffee"></script>
</body>
</html>

External file example (app.coffee):

# app.coffee
class App
  constructor: ->
    @setupEventListeners()
    @render()
  
  setupEventListeners: ->
    document.addEventListener 'DOMContentLoaded', => @onDOMReady()
  
  onDOMReady: ->
    console.log 'App ready!'
    @bindButtons()
  
  bindButtons: ->
    buttons = document.querySelectorAll 'button'
    for button in buttons
      button.addEventListener 'click', @handleClick
  
  handleClick: (event) =>
    console.log 'Button clicked:', event.target.textContent

# Initialize app
app = new App()

Browser Compiler Variants

CoffeeScript provides two browser compiler builds for different compatibility needs.

Modern Browser Compiler

Optimized for modern browsers with ES6+ support.

Features:

  • Smaller file size
  • ES6+ features enabled
  • Modern JavaScript output
  • Better performance

Include in HTML:

<script src="https://unpkg.com/coffeescript@2.7.0/lib/coffeescript-browser-compiler-modern/coffeescript.js"></script>

or locally:

<script src="node_modules/coffeescript/lib/coffeescript-browser-compiler-modern/coffeescript.js"></script>

Legacy Browser Compiler

Compatible with older browsers including IE11.

Features:

  • Broader browser compatibility
  • ES5 compatible output
  • Polyfills included
  • Larger file size

Include in HTML:

<script src="https://unpkg.com/coffeescript@2.7.0/lib/coffeescript-browser-compiler-legacy/coffeescript.js"></script>

XHR Loading

CoffeeScript can automatically load and compile remote .coffee files via XMLHttpRequest.

Automatic XHR Loading

<!DOCTYPE html>
<html>
<head>
  <script src="coffeescript.js"></script>
</head>
<body>
  <!-- Automatically loads and compiles remote .coffee files -->
  <script type="text/coffeescript" src="https://example.com/utils.coffee"></script>
  <script type="text/coffeescript" src="/js/app.coffee"></script>
</body>
</html>

Manual XHR Loading

// Manual loading and compilation
function loadCoffeeScript(url, callback) {
  const xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
      try {
        const compiled = CoffeeScript.compile(xhr.responseText, {
          filename: url,
          inlineMap: true
        });
        eval(compiled);
        callback && callback(null);
      } catch (error) {
        callback && callback(error);
      }
    }
  };
  xhr.send();
}

// Usage
loadCoffeeScript('/js/module.coffee', function(error) {
  if (error) {
    console.error('Failed to load CoffeeScript:', error);
  } else {
    console.log('CoffeeScript module loaded successfully');
  }
});

Source Map Support

Browser compilation includes automatic source map generation for debugging.

Automatic Source Maps

const CoffeeScript = require('coffeescript');

// Browser compile automatically includes inline source maps
const compiled = CoffeeScript.compile(`
  square = (x) -> x * x
  console.log square 5
`, { 
  filename: 'math.coffee',
  inlineMap: true 
});

console.log(compiled);
// Output includes: //# sourceMappingURL=data:application/json;base64,...

Debugging with Source Maps

When source maps are enabled, browser dev tools show original CoffeeScript:

  1. Chrome DevTools: Source maps automatically detected, CoffeeScript files appear in Sources tab
  2. Firefox DevTools: Original CoffeeScript visible in Debugger tab
  3. Stack Traces: Errors point to CoffeeScript line numbers instead of generated JavaScript
# debug.coffee
class MathUtils
  @square: (x) ->
    debugger  # Browser will break here in CoffeeScript source
    x * x
  
  @factorial: (n) ->
    throw new Error "Negative numbers not supported" if n < 0
    return 1 if n <= 1
    n * @factorial n - 1

console.log MathUtils.square 5
console.log MathUtils.factorial 5

Performance Optimization

Pre-compilation for Production

For production, compile CoffeeScript files beforehand to avoid client-side compilation:

# Compile for production
coffee -c -o js/ src/

# Minify compiled JavaScript
uglifyjs js/app.js -o js/app.min.js
<!-- Production: use pre-compiled JavaScript -->
<script src="js/app.min.js"></script>

Compilation Caching

Cache compiled results to avoid repeated compilation:

const compilationCache = new Map();

function compileCoffeeScript(code, filename) {
  const cacheKey = filename || code;
  
  if (compilationCache.has(cacheKey)) {
    return compilationCache.get(cacheKey);
  }
  
  const compiled = CoffeeScript.compile(code, {
    filename,
    inlineMap: true
  });
  
  compilationCache.set(cacheKey, compiled);
  return compiled;
}

Lazy Loading

Load and compile CoffeeScript modules on demand:

const moduleCache = new Map();

async function loadCoffeeModule(url) {
  if (moduleCache.has(url)) {
    return moduleCache.get(url);
  }
  
  const response = await fetch(url);
  const coffeeCode = await response.text();
  
  const compiled = CoffeeScript.compile(coffeeCode, {
    filename: url,
    bare: true
  });
  
  // Create module-like environment
  const module = { exports: {} };
  const moduleFunction = new Function('module', 'exports', compiled);
  moduleFunction(module, module.exports);
  
  moduleCache.set(url, module.exports);
  return module.exports;
}

// Usage
loadCoffeeModule('/js/utils.coffee').then(utils => {
  console.log('Utils loaded:', utils);
});

Browser Environment Detection

CoffeeScript automatically detects browser environments and adjusts behavior:

// Browser detection (internal)
if (typeof window !== "undefined" && window !== null) {
  // Browser-specific features enabled
  // - Script tag processing
  // - XHR loading
  // - Inline source maps
}

Manual Browser Detection

# Detect environment in CoffeeScript
if typeof window isnt 'undefined'
  # Browser environment
  console.log 'Running in browser'
  
  # DOM ready handling
  document.addEventListener 'DOMContentLoaded', ->
    console.log 'DOM is ready'
    
else if typeof global isnt 'undefined'
  # Node.js environment  
  console.log 'Running in Node.js'
  
else
  # Other environment (Web Worker, etc.)
  console.log 'Running in other environment'

Error Handling

Browser compilation provides user-friendly error handling:

<script>
  try {
    CoffeeScript.run(`
      invalid -> -> syntax
    `);
  } catch (error) {
    console.error('CoffeeScript compilation error:', error.message);
    console.error('Location:', error.location);
    
    // Display user-friendly error
    const errorDiv = document.createElement('div');
    errorDiv.style.color = 'red';
    errorDiv.style.fontFamily = 'monospace';
    errorDiv.textContent = `CoffeeScript Error: ${error.message}`;
    document.body.appendChild(errorDiv);
  }
</script>

Advanced Browser Integration

Web Workers

// main.js
const worker = new Worker('worker.js');
worker.postMessage({ coffee: 'square = (x) -> x * x; square 5' });

// worker.js
importScripts('coffeescript.js');

self.onmessage = function(event) {
  try {
    const result = CoffeeScript.eval(event.data.coffee);
    self.postMessage({ result });
  } catch (error) {
    self.postMessage({ error: error.message });
  }
};

Service Workers

// service-worker.js
importScripts('coffeescript.js');

// Compile CoffeeScript files on-the-fly
self.addEventListener('fetch', event => {
  if (event.request.url.endsWith('.coffee')) {
    event.respondWith(
      fetch(event.request)
        .then(response => response.text())
        .then(coffeeCode => {
          const compiled = CoffeeScript.compile(coffeeCode);
          return new Response(compiled, {
            headers: { 'Content-Type': 'application/javascript' }
          });
        })
    );
  }
});