or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

ast-operations.mdbrowser-integration.mdindex.mdplugin-system.mdtransformation.mdutilities.md
tile.json

browser-integration.mddocs/

Browser Integration

Browser-specific API for client-side JavaScript transformation, script loading from URLs, and automatic transpilation of script tags in web pages.

Capabilities

Run Function

Transforms and immediately executes JavaScript code in the browser environment.

/**
 * Transform and execute code in browser
 * @param {string} code - JavaScript code to transform and execute
 * @param {Object} opts - Transformation options (optional, defaults to {})
 * @returns {any} Result of code execution
 */
function run(code, opts);

Usage Examples:

// In browser environment
const babel = require("babel-core"); // or load via script tag

// Transform and execute ES6 code
const result = babel.run(`
  const greeting = (name) => \`Hello, \${name}!\`;
  return greeting("World");
`, {
  presets: ["es2015"]
});
console.log(result); // "Hello, World!"

// Execute with custom options
const result = babel.run(`
  class Calculator {
    add(a, b) { return a + b; }
  }
  const calc = new Calculator();
  return calc.add(5, 3);
`, {
  presets: ["es2015"],
  filename: "inline-calculator"
});
console.log(result); // 8

Load Function

Loads JavaScript from a URL, transforms it, and optionally executes it.

/**
 * Load and transform script from URL
 * @param {string} url - URL to load script from
 * @param {Function} callback - Callback function called after loading
 * @param {Object} opts - Transformation options (optional, defaults to {})
 * @param {boolean} hold - Whether to hold execution (optional, defaults to false)
 */
function load(url, callback, opts, hold);

Usage Examples:

// Load and auto-execute script
babel.load("https://example.com/script.js", function(transformedCode) {
  console.log("Script loaded and executed");
  console.log("Transformed code:", transformedCode);
}, {
  presets: ["es2015"]
});

// Load without executing (hold = true)
babel.load("https://example.com/library.js", function(transformedCode) {
  console.log("Script loaded but not executed");
  // Manually execute if needed
  eval(transformedCode[0]); // transformedCode is [code, opts] array
}, {
  presets: ["es2015"],  
  filename: "external-library"
}, true);

// Load with error handling
babel.load("https://example.com/script.js", function(transformedCode) {
  try {
    console.log("Script executed successfully");
  } catch (err) {
    console.error("Execution error:", err);
  }
}, {
  presets: ["react", "es2015"]
});

Automatic Script Processing

Babel automatically processes script tags with specific MIME types when loaded in the browser.

// Supported script types (automatically processed):
const SUPPORTED_TYPES = [
  "text/ecmascript-6",
  "text/6to5", 
  "text/babel",
  "module"
];

Usage Examples:

<!-- HTML page with auto-processed scripts -->
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/babel-core@6.26.3/browser.js"></script>
</head>
<body>
  <!-- These scripts are automatically transformed -->
  <script type="text/babel">
    const greeting = (name) => `Hello, ${name}!`;
    console.log(greeting("Browser"));
  </script>
  
  <script type="text/ecmascript-6">
    class MyClass {
      constructor(value) {
        this.value = value;
      }
      
      getValue() {
        return this.value;
      }
    }
    
    const instance = new MyClass(42);
    console.log(instance.getValue());
  </script>
  
  <!-- External script with transformation -->
  <script type="text/babel" src="external-es6-script.js"></script>
</body>
</html>

Browser-Specific Configuration

Browser Environment Detection

// Browser-specific options and behavior
interface BrowserOptions {
  filename?: string;       // Default: "embedded" for inline scripts
  sourceType?: "script";   // Browser scripts are typically "script" mode
  
  // Browser-specific features
  compact?: boolean;       // Minimize output for bandwidth
  comments?: boolean;      // Remove comments to reduce size
  
  // Development options
  sourceMaps?: "inline";   // Inline source maps for debugging
  
  // Plugin configuration
  presets?: Array<string>; // Browser-compatible presets
  plugins?: Array;         // Browser-compatible plugins
}

Browser Environment Setup

// Manual script processing setup
if (typeof window !== 'undefined') {
  // Browser environment
  const babel = window.Babel || require("babel-core");
  
  // Process all babel scripts on page load
  document.addEventListener('DOMContentLoaded', function() {
    const scripts = document.querySelectorAll(
      'script[type="text/babel"], script[type="text/ecmascript-6"]'
    );
    
    scripts.forEach(script => {
      const code = script.innerHTML;
      const transformed = babel.transform(code, {
        presets: ['es2015']
      });
      
      // Execute transformed code
      eval(transformed.code);
    });
  });
}

AJAX and Dynamic Loading

Dynamic Script Loading

// Load and transform scripts dynamically
function loadBabelScript(url, options = {}) {
  return new Promise((resolve, reject) => {
    babel.load(url, function(transformedParams) {
      if (Array.isArray(transformedParams)) {
        // Hold mode - returns [code, opts]
        resolve(transformedParams[0]);
      } else {
        // Auto-execute mode
        resolve(transformedParams);
      }
    }, {
      presets: ['es2015'],
      ...options
    }, true); // hold = true for promise control
  });
}

// Usage
loadBabelScript('https://example.com/module.js')
  .then(transformedCode => {
    console.log('Script loaded and transformed');
    eval(transformedCode); // Execute when ready
  })
  .catch(err => {
    console.error('Failed to load script:', err);
  });

Fetch Integration

// Combine with fetch API for modern loading
async function fetchAndTransform(url, options = {}) {
  try {
    const response = await fetch(url);
    const code = await response.text();
    
    const result = babel.transform(code, {
      presets: ['es2015'],
      filename: url,
      ...options
    });
    
    return result.code;
  } catch (err) {
    console.error('Fetch and transform error:', err);
    throw err;
  }
}

// Usage
fetchAndTransform('https://example.com/es6-module.js')
  .then(transformedCode => {
    // Create and execute script element
    const script = document.createElement('script');
    script.textContent = transformedCode;
    document.head.appendChild(script);
  });

Automatic Script Processing

Babel Core automatically processes script tags with specific MIME types when loaded in the browser, providing seamless ES6+ support without manual intervention.

Supported Script Types

// Automatically processed script MIME types:
const supportedTypes = [
  "text/ecmascript-6",
  "text/6to5", 
  "text/babel",
  "module"
];

Usage Examples:

<!-- Automatic ES6 transformation -->
<script type="text/babel">
  const greeting = (name) => `Hello, ${name}!`;
  const message = greeting("World");
  console.log(message);
</script>

<!-- Module script transformation -->
<script type="module">
  import { transform } from './utils.js';
  const result = transform([1, 2, 3]);
  console.log(result);
</script>

<!-- Legacy 6to5 compatibility -->
<script type="text/6to5">
  class Calculator {
    add(a, b) { return a + b; }
  }
  const calc = new Calculator();
  console.log(calc.add(5, 3));
</script>

Automatic Loading Behavior

// Babel automatically:
// 1. Scans for script tags with supported types on DOMContentLoaded
// 2. Transforms inline scripts and loads external scripts
// 3. Maintains execution order across script dependencies
// 4. Handles both src and inline script content

// External script processing
<script type="text/babel" src="./my-es6-module.js"></script>

// Mixed processing (maintains order)
<script type="text/babel" src="./module1.js"></script>
<script type="text/babel">
  // This runs after module1.js is loaded and transformed
  console.log("Module 1 loaded, running inline script");
</script>
<script type="text/babel" src="./module2.js"></script>

Configuration for Auto-Processing

// Configure automatic processing (must be before script includes)
<script>
  // Default babel configuration for auto-processed scripts
  window.babelOptions = {
    presets: ['es2015', 'react'],
    plugins: ['transform-object-rest-spread']
  };
</script>
<script src="babel-core.js"></script>

<!-- Auto-processed with global config -->
<script type="text/babel">
  const { Component } = React;
  class MyComponent extends Component {
    render() {
      return <div>Hello World</div>;
    }
  }
</script>

Manual Control of Auto-Processing

// Disable automatic processing
<script>
  window.babelAutoProcess = false;
</script>
<script src="babel-core.js"></script>

// Manual script processing
<script>
  document.addEventListener('DOMContentLoaded', function() {
    const scripts = document.querySelectorAll('script[type="text/babel"]');
    scripts.forEach(script => {
      if (script.src) {
        babel.load(script.src, null, { presets: ['es2015'] });
      } else {
        babel.run(script.innerHTML, { presets: ['es2015'] });
      }
    });
  });
</script>

Browser Compatibility

Polyfills and Dependencies

// Required polyfills for older browsers
if (!window.Promise) {
  // Promise polyfill required
  console.warn('Promise polyfill required for Babel browser usage');
}

if (!window.fetch) {
  // Fetch polyfill for dynamic loading
  console.warn('Fetch polyfill recommended for dynamic script loading');
}

// Core dependencies (automatically included in browser build)
// - babylon (parser)
// - babel-generator (code generation) 
// - babel-traverse (AST traversal)
// - babel-types (AST utilities)

Performance Considerations

// Browser optimization strategies
const optimizedOptions = {
  // Reduce output size
  compact: true,
  comments: false,
  
  // Minimize source maps for production
  sourceMaps: process.env.NODE_ENV === 'development' ? 'inline' : false,
  
  // Use minimal preset for faster transformation
  presets: [
    ['es2015', { 
      modules: false,    // Keep ES6 modules for bundlers
      loose: true       // Faster, less strict transformation
    }]
  ],
  
  // Cache transformation results
  cacheDirectory: true  // If supported by environment
};

// Batch process multiple scripts
const scripts = document.querySelectorAll('script[type="text/babel"]');
const transformPromises = Array.from(scripts).map(script => {
  return babel.transform(script.innerHTML, optimizedOptions);
});

Promise.all(transformPromises).then(results => {
  results.forEach((result, index) => {
    eval(result.code);
  });
});

Error Handling

Browser-specific error handling patterns:

// Global error handler for babel transformations
window.addEventListener('error', function(event) {
  if (event.error && event.error._babel) {
    console.error('Babel transformation error:', event.error.message);
    console.error('Code frame:', event.error.codeFrame);
    
    // Show user-friendly error message
    const errorDiv = document.createElement('div');
    errorDiv.innerHTML = `
      <h3>Script Transformation Error</h3>
      <pre>${event.error.message}</pre>
      <pre>${event.error.codeFrame || ''}</pre>
    `;
    errorDiv.style.cssText = 'background: #ffebee; padding: 10px; margin: 10px; border-left: 4px solid #f44336;';
    document.body.insertBefore(errorDiv, document.body.firstChild);
  }
});

// Safe transformation wrapper
function safeTransform(code, options) {
  try {
    return babel.transform(code, options);
  } catch (err) {
    console.error('Transformation failed:', err);
    
    // Return original code as fallback
    return { 
      code: code, 
      map: null, 
      ast: null,
      error: err
    };
  }
}