CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-parcel--transformer-js

JavaScript and TypeScript transformer plugin for the Parcel bundler with JSX, React, and modern JavaScript support

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

index.mddocs/

Parcel JavaScript Transformer

@parcel/transformer-js is a JavaScript and TypeScript transformer plugin for the Parcel bundler. It provides comprehensive JavaScript compilation, transformation, and optimization capabilities including JSX support, TypeScript compilation, React Fast Refresh, and environment-specific transformations.

Package Information

  • Package Name: @parcel/transformer-js
  • Package Type: npm
  • Language: JavaScript/TypeScript
  • Installation: npm install @parcel/transformer-js

Core Imports

The transformer is typically used as a Parcel plugin and not imported directly. However, internal utilities are available:

// Main transformer (for plugin development) - ES module default export
import JSTransformer from "@parcel/transformer-js";

// ESModule helpers (internal runtime support) - CommonJS exports
const { interopDefault, defineInteropFlag, exportAll, export } = require("@parcel/transformer-js/src/esmodule-helpers");

// MDX components (for MDX transformation) - ES module export
import { useMDXComponents } from "@parcel/transformer-js/src/mdx-components.jsx";

For plugin registration (Parcel configuration):

// .parcelrc
{
  "transformers": {
    "*.{js,mjs,jsx,cjs,ts,tsx}": ["@parcel/transformer-js"]
  }
}

Basic Usage

This transformer is automatically used by Parcel for JavaScript and TypeScript files. Configuration is typically done through:

// tsconfig.json
{
  "compilerOptions": {
    "jsx": "react-jsx",
    "jsxImportSource": "react",
    "experimentalDecorators": true,
    "useDefineForClassFields": true,
    "target": "es2022"
  }
}

Package-level configuration:

// package.json
{
  "@parcel/transformer-js": {
    "inlineFS": false,
    "inlineEnvironment": ["NODE_ENV", "DEBUG"],
    "unstable_inlineConstants": true
  }
}

Architecture

The transformer is built on several key components:

  • Parcel Plugin Interface: Implements Parcel's Transformer interface with loadConfig and transform methods
  • Rust Core: Performance-critical transformations implemented in Rust for speed
  • Configuration System: Automatic detection of JSX libraries, TypeScript settings, and build targets
  • Runtime Helpers: ES module interoperability functions for generated code
  • Environment Targeting: Browser compatibility, Node.js, and Electron targeting via browserslist

Capabilities

JavaScript/TypeScript Transformation

Core transformation functionality for modern JavaScript and TypeScript files with automatic configuration detection.

/**
 * Main transformer instance - implements Parcel's Transformer interface
 * Supports: JS, JSX, TS, TSX, MDX files
 * Default export is a configured Transformer instance
 */
const JSTransformer: Transformer;
export default JSTransformer;

interface TransformerConfig {
  isJSX?: boolean;
  automaticJSXRuntime?: boolean;
  jsxImportSource?: string;
  pragma?: string;
  pragmaFrag?: string;
  inlineEnvironment?: boolean | string[];
  inlineFS?: boolean;
  inlineConstants?: boolean;
  reactRefresh?: boolean;
  decorators?: boolean;
  useDefineForClassFields?: boolean;
}

ESModule Runtime Helpers

Utility functions for ES module interoperability in generated code.

/**
 * Provides default export interop for CommonJS modules
 * Returns the module as-is if it has __esModule, otherwise wraps it with {default: module}
 * @param a - Module to provide interop for
 * @returns Module with default property if needed
 */
function interopDefault(a: any): any;

/**
 * Defines __esModule property on exports object using Object.defineProperty
 * @param a - Exports object to mark as ES module
 */
function defineInteropFlag(a: object): void;

/**
 * Copies all enumerable properties from source to dest using getters
 * Excludes 'default', '__esModule', and existing properties in dest
 * @param source - Source object to copy from
 * @param dest - Destination object to copy to
 * @returns Destination object
 */
function exportAll(source: object, dest: object): object;

/**
 * Defines a single named export with getter using Object.defineProperty
 * @param dest - Destination object
 * @param destName - Property name to define
 * @param get - Getter function for the property
 */
function export(dest: object, destName: string, get: () => any): void;

MDX Component Support

Default components for MDX file transformation.

/**
 * Returns default MDX component mappings
 * @returns Object containing default components (currently includes CodeBlock)
 */
function useMDXComponents(): {
  CodeBlock: React.ComponentType<CodeBlockProps>;
};

/**
 * Default code block component for MDX rendering
 * Renders a <pre><code> block with optional language class and additional render content
 */
interface CodeBlockProps {
  lang?: string;
  children: React.ReactNode;
  render?: React.ReactNode;
}

/**
 * CodeBlock component implementation
 * Renders code within pre/code tags with language-specific CSS class
 */
const CodeBlock: React.ComponentType<CodeBlockProps>;

Configuration Schema

JSON schema for package-level transformer configuration.

interface ConfigOptions {
  /**
   * Whether to inline filesystem calls (default: true unless browser.fs = false)
   */
  inlineFS?: boolean;
  
  /**
   * Environment variable inlining configuration
   * - boolean: inline all (true) or only NODE_ENV (false)
   * - string[]: glob patterns for environment variables to inline
   */
  inlineEnvironment?: boolean | string[];
  
  /**
   * Whether to inline constants (experimental feature)
   */
  unstable_inlineConstants?: boolean;
}

// JSON schema definition used internally for validation
const CONFIG_SCHEMA: {
  type: 'object';
  properties: {
    inlineFS: { type: 'boolean' };
    inlineEnvironment: {
      oneOf: [
        { type: 'boolean' };
        { type: 'array'; items: { type: 'string' } };
      ];
    };
    unstable_inlineConstants: { type: 'boolean' };
  };
  additionalProperties: false;
};

JSX and TypeScript Support

Automatic configuration for JSX and TypeScript based on dependencies and tsconfig.json.

Supported JSX Libraries:

// JSX pragma configurations for different libraries
interface JSXPragmaConfig {
  pragma: string;
  pragmaFrag?: string;
  automatic?: string; // Version range for automatic JSX runtime
}

const JSX_PRAGMA: {
  react: {
    pragma: 'React.createElement';
    pragmaFrag: 'React.Fragment';
    automatic: '>= 17.0.0 || ^16.14.0 || >= 0.0.0-0 < 0.0.0';
  };
  preact: {
    pragma: 'h';
    pragmaFrag: 'Fragment';
    automatic: '>= 10.5.0';
  };
  nervjs: {
    pragma: 'Nerv.createElement';
    pragmaFrag: undefined;
    automatic: undefined;
  };
  hyperapp: {
    pragma: 'h';
    pragmaFrag: undefined;
    automatic: undefined;
  };
};
  • React (with automatic JSX runtime detection for React 17+)
  • Preact
  • Nerv
  • Hyperapp

TypeScript Compiler Options:

interface TSConfig {
  compilerOptions?: {
    jsx?: 'react' | 'react-jsx' | 'react-jsxdev' | 'preserve' | 'react-native';
    jsxFactory?: string;
    jsxFragmentFactory?: string;
    jsxImportSource?: string;
    experimentalDecorators?: boolean;
    useDefineForClassFields?: boolean;
    target?: string;
  };
}

Environment Targeting

Automatic browser and runtime targeting based on configuration.

Supported Targets:

// Browser name mapping for target compilation
const BROWSER_MAPPING: Record<string, string | null>;

// Browser exclusion rules for ES module targeting
const ESMODULE_BROWSERS: string[];
  • Browser compatibility via browserslist
  • Node.js version targeting
  • Electron application support
  • ES module vs. script targeting
  • Web Workers and Service Workers
  • Worklets

Target Detection:

  • package.json browserslist field
  • .browserslistrc file
  • engines.node for Node.js targeting
  • engines.electron for Electron apps

Development Features

Development-specific functionality for enhanced developer experience.

Features:

// Macro context for compile-time code generation
interface MacroAsset {
  type: string;
  content: string;
}

interface MacroContext {
  addAsset(asset: MacroAsset): void;
  loc: SourceLocation;
  invalidateOnFileChange(path: string): void;
  invalidateOnFileCreate(invalidation: FileCreateInvalidation): void;
  invalidateOnEnvChange(env: string): void;
  invalidateOnStartup(): void;
  invalidateOnBuild(): void;
}
  • React Fast Refresh integration
  • Hot module replacement support
  • Source map generation and preservation
  • Diagnostic error reporting with hints
  • Macro system for compile-time code generation

Build Optimizations

Production build optimizations applied automatically.

Optimizations:

// File extensions that enable JSX parsing
const JSX_EXTENSIONS: {
  jsx: true;
  tsx: true;
};

// Browser name mapping for target compilation
const BROWSER_MAPPING: {
  and_chr: 'chrome';
  and_ff: 'firefox';
  ie_mob: 'ie';
  ios_saf: 'ios';
  op_mob: 'opera';
  and_qq: null;
  and_uc: null;
  baidu: null;
  bb: null;
  kaios: null;
  op_mini: null;
};

// Browser exclusion rules for ES module targeting
const ESMODULE_BROWSERS: string[];
  • Tree shaking preparation
  • Constant folding and inlining
  • Environment variable replacement
  • Dead code elimination
  • Scope hoisting compatibility
  • Bundle splitting support

Error Handling

The transformer provides context-specific error messages for different execution environments:

interface ScriptError {
  message: string;
  hint: string;
}

// Environment-specific errors for imports/exports in wrong contexts
const SCRIPT_ERRORS: {
  browser: ScriptError;
  'web-worker': ScriptError;
  'service-worker': ScriptError;
}

Required Type Definitions

// Core Parcel types referenced in APIs
interface SourceLocation {
  filePath: string;
  start: {
    line: number;
    column: number;
  };
  end: {
    line: number;
    column: number;
  };
}

interface FileCreateInvalidation {
  glob: string;
}

// TypeScript compiler configuration interface
interface TSConfig {
  compilerOptions?: {
    jsx?: 'react' | 'react-jsx' | 'react-jsxdev' | 'preserve' | 'react-native';
    jsxFactory?: string;
    jsxFragmentFactory?: string;
    jsxImportSource?: string;
    experimentalDecorators?: boolean;
    useDefineForClassFields?: boolean;
    target?: string;
  };
}

// Macro context interface for compile-time code generation
interface MacroContext {
  addAsset(asset: MacroAsset): void;
  loc: SourceLocation;
  invalidateOnFileChange(filePath: string): void;
  invalidateOnFileCreate(invalidation: FileCreateInvalidation): void;
  invalidateOnEnvChange(env: string): void;
  invalidateOnStartup(): void;
  invalidateOnBuild(): void;
}

interface MacroAsset {
  type: string;
  content: string;
}

interface Asset {
  // Parcel Asset interface details
}

interface Transformer {
  // Parcel Transformer interface details
}

Integration Notes

This transformer integrates deeply with the Parcel ecosystem:

  • @parcel/plugin: Base transformer interface
  • @parcel/rust: Rust transformation bindings for performance
  • @parcel/diagnostic: Structured error reporting
  • @parcel/source-map: Source map handling and composition
  • @parcel/utils: Common utilities and validation
  • @parcel/workers: Multi-threaded transformation processing

External dependencies include browserslist for browser targeting, semver for version comparisons, and various runtime helpers for generated code compatibility.

Install with Tessl CLI

npx tessl i tessl/npm-parcel--transformer-js

docs

index.md

tile.json