C# to JavaScript compiler

# Output Types

h5 allows you to configure how your C# code is compiled into JavaScript modules. This is controlled by the module setting in h5.json and the [Module] attribute.

# Module Systems

h5 supports several JavaScript module systems, allowing you to integrate your code with different environments and bundlers.

# Supported Module Types

  • None (Default): Creates global variables for your namespaces and types. Suitable for script tags in HTML.
  • AMD: Asynchronous Module Definition, used by RequireJS.
  • CommonJS: Synchronous module loading, used by Node.js and older bundlers.
  • ES6: ECMAScript 6 Modules (ESM), standard in modern browsers and tools.
  • UMD: Universal Module Definition, compatible with AMD, CommonJS, and global scripts.

# Configuration

You can set the default module type for your entire assembly in h5.json:

{
  "module": "CommonJS"
}

Or apply it to specific classes using the [Module] attribute:

using H5;

[Module(ModuleType.CommonJS)]
public class MyModuleClass
{
    // ...
}

# Mixing Module Types

It is possible to mix module types within the same project. For example, you might want your core library to be CommonJS but a specific component to be an ES6 module.

# Output Structure

Depending on the module setting, the generated JavaScript code will look different:

# No Module (Global)

// Global scope
var MyNamespace = {
    MyClass: function() { ... }
};

# CommonJS

var H5 = require("h5");
// ... implementation
module.exports = {
    MyClass: MyClass
};

# ES6 Modules

import { System } from "h5";
// ... implementation
export class MyClass { ... }

# Using Modules

When using module systems, you need to ensure your environment supports them or use a bundler (like Webpack, Rollup, or Vite) to package your application.

# Loading External Modules

You can also import external JavaScript modules into your C# code using the [Module] attribute on an external class definition.

[External]
[Module("react")] // Imports 'react' module
public static class React
{
    public static extern object CreateElement(string type, object props, params object[] children);
}

This tells the compiler to generate an import statement for react when this class is used.