Skip to content

Create esbuild compile script for JSX transformation #201

@rafbcampos

Description

@rafbcampos

Description

Create a compile script that uses esbuild to transform JSX code into calls to our custom createElement function. This script will be the entry point for compiling content authored with our DSL.

Tasks

  • Create compile function that accepts entry point and output options
  • Configure esbuild with appropriate JSX options (jsxFactory and jsxFragment)
  • Set up bundling options for esbuild
  • Create an esbuild plugin to inject the necessary imports from our JSX runtime
  • Handle source maps generation
  • Add error handling and reporting
  • Create utility functions for file path resolution
  • Add tests for compile script with various input files

Technical Details

export async function compile(options: CompileOptions): Promise<void> {
  const { entryPoint, output, sourceMap = false, minify = false } = options;
  
  await esbuild.build({
    entryPoints: [entryPoint],
    outfile: output,
    bundle: true,
    sourcemap: sourceMap,
    minify,
    format: 'esm',
    platform: 'neutral',
    jsx: 'transform',
    jsxFactory: 'createElement',
    jsxFragment: 'Fragment',
    external: ['react', 'react-dom'],
    write: true,
    define: {
      'process.env.NODE_ENV': '"production"'
    }
  });
}

const jsxPrelude = `
import { createElement, Fragment, useState, useEffect, useContext, useRef } from './jsx-runtime';
`;


// esbuild plugin to inject imports
export function jsxRuntimePlugin(): esbuild.Plugin {
    return {
        name: 'jsx-runtime-injector',
        setup(build) {
            build.onLoad({ filter: /\.(jsx|tsx)$/ }, async (args) => {
                const source = await fs.promises.readFile(args.path, 'utf8');
                const contents = `${jsxPrelude}\n${source}`;

                return {
                    contents,
                    loader: args.path.endsWith('.tsx') ? 'tsx' : 'jsx'
                };
            });
        }
    };
}

Acceptance Criteria:

  • Compile script successfully transforms JSX code using our custom createElement and Fragment
  • Bundle is generated correctly with appropriate format
  • Source maps are generated when requested
  • Error handling provides useful error messages
  • Tests demonstrate successful compilation of simple JSX files

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions