or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

ast-types.mdbrowser.mdcli.mdindex.mdmodules.mdregistration.mdtransformation.mdtransformers.md
tile.json

browser.mddocs/

Browser API

Browser-specific functionality for client-side usage. The browser API enables 6to5 to work directly in web browsers for development, prototyping, and client-side transformation.

Browser API Functions

Code Execution

/**
 * Transform and execute ES6+ code immediately in browser
 * @param code - ES6+ source code to transform and run
 * @param opts - Transformation options
 * @returns Result of code execution
 */
function run(code: string, opts?: TransformOptions): any;

Script Loading

/**
 * Load external script, transform it, and optionally execute
 * @param url - URL of script to load
 * @param callback - Optional callback with [transformedCode, options]
 * @param opts - Transformation options
 * @param hold - If true, don't execute immediately
 */
function load(url: string, callback?: LoadCallback, opts?: TransformOptions, hold?: boolean): void;

type LoadCallback = (param: [string, TransformOptions]) => void;

Core Transform

The browser API also exposes the core transform function:

/**
 * Transform ES6+ code to ES5 (same as Node.js API)
 * @param code - Source code to transform
 * @param opts - Transformation options
 * @returns Transform result
 */
function transform(code: string, opts?: TransformOptions): TransformResult;

/**
 * Package version
 */
const version: string;

Automatic Script Processing

The browser API automatically processes script tags with special type attributes:

Supported Script Types

<!-- ES6 module type -->
<script type="text/ecmascript-6">
  class MyClass {
    constructor(name) {
      this.name = name;
    }
  }
</script>

<!-- 6to5 specific type -->
<script type="text/6to5">
  const arrow = () => "Hello World";
  console.log(arrow());
</script>

<!-- Module type -->
<script type="module">
  import { Component } from './component.js';
  const app = new Component();
</script>

Usage Examples

Basic Browser Usage

<!DOCTYPE html>
<html>
<head>
  <!-- Include 6to5 browser build -->
  <script src="node_modules/6to5/lib/6to5/api/browser.js"></script>
</head>
<body>
  <!-- ES6+ code in script tags -->
  <script type="text/6to5">
    class Greeter {
      constructor(name) {
        this.name = name;
      }
      
      greet() {
        return `Hello, ${this.name}!`;
      }
    }
    
    const greeter = new Greeter("World");
    document.body.innerHTML = greeter.greet();
  </script>
</body>
</html>

Interactive Code Execution

<script src="6to5-browser.js"></script>
<script>
  // Transform and run code dynamically
  const es6Code = `
    const multiply = (a, b) => a * b;
    const numbers = [1, 2, 3, 4, 5];
    const doubled = numbers.map(n => multiply(n, 2));
    doubled;
  `;
  
  const result = to5.run(es6Code, {
    modules: "ignore" // No module transformation in browser
  });
  
  console.log("Result:", result); // [2, 4, 6, 8, 10]
</script>

External Script Loading

<script src="6to5-browser.js"></script>
<script>
  // Load external ES6+ file
  to5.load("./components/my-component.js", function(param) {
    console.log("Component loaded and transformed");
    // param[0] contains transformed code
    // param[1] contains options used
  }, {
    modules: "ignore",
    optional: ["es7.objectRestSpread"]
  });
  
  // Load but don't execute immediately
  to5.load("./utils/helpers.js", function(param) {
    // Manually execute when ready
    const helperResult = to5.run.apply(to5, param);
    console.log("Helpers loaded:", helperResult);
  }, {
    runtime: false
  }, true); // hold = true
</script>

Development Workflow

<!DOCTYPE html>
<html>
<head>
  <script src="6to5-browser.js"></script>
  <style>
    .error { color: red; font-family: monospace; }
    .result { color: green; font-weight: bold; }
  </style>
</head>
<body>
  <h1>ES6+ Playground</h1>
  
  <textarea id="code" rows="10" cols="80">
// Try ES6+ code here
class Calculator {
  add(a, b) { return a + b; }
  multiply = (a, b) => a * b; // ES7 property
}

const calc = new Calculator();
const result = calc.add(5, calc.multiply(2, 3));
console.log(`Result: ${result}`);
result;
  </textarea>
  
  <br><button onclick="runCode()">Run Code</button>
  
  <div id="output"></div>
  
  <script>
    function runCode() {
      const code = document.getElementById('code').value;
      const output = document.getElementById('output');
      
      try {
        const result = to5.run(code, {
          optional: ["es7.objectRestSpread"],
          playground: true
        });
        
        output.innerHTML = `<div class="result">Result: ${result}</div>`;
      } catch (error) {
        output.innerHTML = `<div class="error">Error: ${error.message}</div>`;
      }
    }
  </script>
</body>
</html>

Module Loading Pattern

<script src="6to5-browser.js"></script>
<script>
  // Simulate module system in browser
  const modules = {};
  
  function loadModule(name, url) {
    return new Promise((resolve, reject) => {
      to5.load(url, function(param) {
        try {
          // Create module context
          const moduleContext = {
            exports: {},
            module: { exports: {} }
          };
          
          // Execute in context
          const moduleCode = `
            (function(exports, module) {
              ${param[0]}
            })
          `;
          
          const moduleFunc = new Function('return ' + moduleCode)();
          moduleFunc(moduleContext.exports, moduleContext.module);
          
          modules[name] = moduleContext.module.exports;
          resolve(modules[name]);
        } catch (error) {
          reject(error);
        }
      }, {
        modules: "common"
      }, true);
    });
  }
  
  // Load modules
  loadModule('utils', './utils.js')
    .then(() => loadModule('app', './app.js'))
    .then(() => {
      console.log('All modules loaded');
      // Start application
      modules.app.start();
    });
</script>

Build Tool Integration

<!-- Development: Use 6to5 in browser -->
<script>
  if (location.hostname === 'localhost') {
    // Development mode
    document.write('<script src="6to5-browser.js"><\/script>');
    document.write('<script type="text/6to5" src="src/app.js"><\/script>');
  } else {
    // Production mode: use pre-compiled
    document.write('<script src="dist/app.js"><\/script>');
  }
</script>

Error Handling

<script src="6to5-browser.js"></script>
<script>
  // Handle transformation errors
  window.addEventListener('error', function(e) {
    if (e.message.includes('6to5')) {
      console.error('6to5 transformation error:', e);
      // Show user-friendly error
      document.body.innerHTML = `
        <div style="color: red; padding: 20px;">
          <h2>Compilation Error</h2>
          <pre>${e.message}</pre>
        </div>
      `;
    }
  });
  
  // Safe code execution
  function safeRun(code, options = {}) {
    try {
      return to5.run(code, options);
    } catch (error) {
      console.error('Runtime error:', error);
      return { error: error.message };
    }
  }
  
  // Example with error handling
  const result = safeRun(`
    const broken = () => {
      throw new Error("Something went wrong");
    };
    broken();
  `);
  
  if (result.error) {
    console.log('Caught error:', result.error);
  }
</script>

Performance Considerations

<script src="6to5-browser.js"></script>
<script>
  // Cache transformed code
  const transformCache = new Map();
  
  function cachedTransform(code, options) {
    const key = JSON.stringify({ code, options });
    
    if (transformCache.has(key)) {
      return transformCache.get(key);
    }
    
    const result = to5.transform(code, options);
    transformCache.set(key, result);
    return result;
  }
  
  // Preload and cache common transformations
  const commonTransforms = [
    'const fn = () => {};',
    'class Component {}',
    'const {a, b} = obj;'
  ];
  
  commonTransforms.forEach(code => {
    cachedTransform(code, { modules: 'ignore' });
  });
</script>

Web Worker Usage

// main.js
const worker = new Worker('transform-worker.js');

worker.postMessage({
  code: 'const result = [1,2,3].map(x => x * 2);',
  options: { modules: 'ignore' }
});

worker.onmessage = function(e) {
  console.log('Transformed code:', e.data.code);
};

// transform-worker.js
importScripts('6to5-browser.js');

self.onmessage = function(e) {
  const { code, options } = e.data;
  
  try {
    const result = to5.transform(code, options);
    self.postMessage({ code: result.code, map: result.map });
  } catch (error) {
    self.postMessage({ error: error.message });
  }
};