### CLI Usage Source: https://github.com/wessberg/cjstoesm/blob/master/README.md Examples of how to use the cjstoesm library from the command line to convert CommonJS files to ESM. ```APIDOC ## CLI Usage You can use this library as a CLI to convert your project files from using CommonJS to using ESM. The following command transforms all files matched by the glob `**/*.*` and overwrites them in-place: ```bash cjstoesm "**/*.*" ``` You can also just pass in a folder name, in which case all direct descendents of that folder will be transformed and overwritten: ```bash cjstoesm "src" ``` You can also pass in a second argument, `outDir`, to avoid overwriting the source files. The following command transforms all files matched by the glob `**/*.*` and emits them to the folder `dist` from the current working directory: ```bash cjstoesm "**/*.*" dist ``` ### CLI Options ``` $ cjstoesm --help Usage: cjstoesm [options] Transforms CJS to ESM modules based on the input glob Options: -d, --debug [arg] Whether to print debug information -v, --verbose [arg] Whether to print verbose information -s, --silent [arg] Whether to not print anything -c, --cwd [arg] Optionally which directory to use as the current working directory -p, --preserve-module-specifiers [arg] Determines whether or not module specifiers are preserved. Possible values are: "external", "internal", "always", and "never" (default: "external") -a, --import-attributes [arg] Determines whether or not Import Attributes are included where they are relevant. Possible values are: true and false (default: true) -m, --dry [arg] If true, no files will be written to disk -h, --help display help for command ``` ``` -------------------------------- ### API Usage Source: https://github.com/wessberg/cjstoesm/blob/master/README.md Examples of how to use the cjstoesm library programmatically within your TypeScript or JavaScript projects. ```APIDOC ## API Usage You can also use this library programmatically: ```ts import {transform} from "cjstoesm"; await transform({ input: "src/**/*.*", outDir: "dist" }); ``` Alternatively, if you don't want the transform function to automatically write files to disk, you can pass `write: false` as an option and handle it yourself: ```ts import {transform} from "cjstoesm"; import {writeFileSync} from "fs"; const result = await transform({ input: "src/**/*.*", write: false }); // Write to disk for (const {fileName, text} of result.files) { writeFileSync(fileName, text); } ``` ### API Options ```typescript interface TransformOptions { /** * The input glob(s) to match against the file system */ input: string[] | string; /** * Optionally, the output directory to use. Defaults to inheriting that of the matched input files` */ outDir?: string; /** * If write is false, no files will be written to disk */ write: boolean; /** * The FileSystem to use. Useful if you want to work with a virtual file system. Defaults to using the "fs" module */ fileSystem: FileSystem; /** * A logger that can print messages of varying severity depending on the log level */ logger: Loggable; /** * The base directory (defaults to process.cwd()) */ cwd: string; /** * Determines how module specifiers are treated. * - external (default): CommonJS module specifiers identifying libraries or built-in modules are preserved (default) * - internal: CommonJS module specifiers identifying anything else than libraries or built-in modules are preserved * - always: CommonJS module specifiers are never transformed. * - never: CommonJS module specifiers are always transformed * It can also take a function that is invoked with a module specifier and returns a boolean determining whether or not it should be preserved */ preserveModuleSpecifiers: | "always" | "never" | "external" | "internal" | ((specifier: string) => boolean); /** * Determines whether or not to include import attributes when converting require() calls referencing JSON files to ESM. * - true (default): Import attributes will always be added when relevant. * - false: Import attributes will never be added. * It can also take a function that is invoked with a module specifier and returns a boolean determining whether or not import attributes should be added */ importAttributes: boolean | ((specifier: string) => boolean); /** * If given, a specific TypeScript version to use */ typescript: typeof TS; /** * If true, debug information will be printed. If a function is provided, it will be invoked for each file name. Returning true from the function * determines that debug information will be printed related to that file */ debug: boolean | string | ((file: string) => boolean); } ``` ``` -------------------------------- ### CommonJS require() to ES Module Conversion Examples Source: https://context7.com/wessberg/cjstoesm/llms.txt Illustrates various scenarios of converting CommonJS require() statements to their ES module import equivalents. Covers basic imports, destructuring, aliasing, property access, and immediate function calls. ```typescript // Input: Basic require const fs = require("fs"); // Output: import fs from "fs"; ``` ```typescript // Input: Destructured require const {readFileSync, writeFileSync} = require("fs"); // Output: import {readFileSync, writeFileSync} from "fs"; ``` ```typescript // Input: Aliased destructuring const {readFileSync: read} = require("fs"); // Output: import {readFileSync as read} from "fs"; ``` ```typescript // Input: Property access on require const join = require("path").join; // Output: import {join as join$0} from "path"; const join = {join: join$0}.join; ``` ```typescript // Input: Immediately invoked require const app = require("express")(); // Output: import express from "express"; const app = express(); ``` ```typescript // Input: Anonymous require in function call myFunction(require("lodash")); // Output: import lodash from "lodash"; myFunction(lodash); ``` ```typescript // Input: Side-effect only require require("./polyfills"); // Output: import "./polyfills.js"; ``` ```typescript // Input: JSON file require (with importAttributes: true) const pkg = require("./package.json"); // Output: import pkg from "./package.json" with {type: "json"}; ``` -------------------------------- ### CommonJS exports/module.exports to ES Module Conversion Examples Source: https://context7.com/wessberg/cjstoesm/llms.txt Demonstrates how various CommonJS export patterns, including named exports, default exports via module.exports assignment, and re-exports, are transformed into ES module syntax. ```typescript // Input: Named exports via exports object exports.foo = 1; exports.bar = function bar() {}; // Output: export const foo = 1; export function bar() {} ``` ```typescript // Input: module.exports assignment module.exports = function myFunc() {}; // Output: export default (function myFunc() {}); ``` ```typescript // Input: module.exports with object literal module.exports = { foo: 1, bar() { return 2; }, baz: new RegExp("") }; // Output: export const foo = 1; export function bar() { return 2; } export const baz = new RegExp(""); export default { foo, bar, baz }; ``` ```typescript // Input: Re-export pattern module.exports = require("./utils"); // Output (when utils has named exports): export * from "./utils.js"; // Output (when utils has default export): export {default} from "./utils.js"; ``` ```typescript // Input: Barrel export pattern exports.utils = require("./utils"); // Output: import * as utils from "./utils.js"; export { utils }; ``` ```typescript // Input: Named export with require export const SomeLib = require("some-lib"); // Output: export { default as SomeLib } from "some-lib"; ``` -------------------------------- ### Webpack Integration with ts-loader and awesome-typescript-loader Source: https://context7.com/wessberg/cjstoesm/llms.txt Demonstrates how to configure Webpack to use cjstoesm for transforming CommonJS to ES modules. It shows setup for both ts-loader and awesome-typescript-loader, utilizing the cjsToEsm custom transformers. ```typescript import {cjsToEsm} from "cjstoesm"; export default { module: { rules: [ { test: /(\.mjs)|(\\.[jt]sx?)$/, loader: "ts-loader", options: { getCustomTransformers: () => cjsToEsm() } } ] } }; ``` ```typescript import {cjsToEsm} from "cjstoesm"; export default { module: { rules: [ { test: /(\.mjs)|(\\.[jt]sx?)$/, loader: "awesome-typescript-loader", options: { getCustomTransformers: () => cjsToEsm() } } ] } }; ``` -------------------------------- ### cjstoesm Transformation Options Configuration Source: https://context7.com/wessberg/cjstoesm/llms.txt Provides an example of configuring the cjstoesm transformation process. It details required and optional parameters such as input glob patterns, output directory, write behavior, module specifier handling, and import attributes for JSON files. ```typescript import {transform} from "cjstoesm"; // Full options example const result = await transform({ // Required: input glob pattern(s) input: ["src/**/*.js", "lib/**/*.ts"], // Optional: output directory (defaults to in-place transformation) outDir: "dist", // Optional: whether to write files to disk (default: true) write: true, // Optional: base directory (default: process.cwd()) cwd: "/path/to/project", // Optional: module specifier handling // - "external": preserve external/built-in module specifiers (default) // - "internal": preserve internal module specifiers // - "always": never transform module specifiers // - "never": always transform module specifiers // - function: custom logic preserveModuleSpecifiers: "external", // Optional: import attributes for JSON files (default: true) // When true: import pkg from "./package.json" with {type: "json"}; importAttributes: true, // Optional: enable debug output debug: false }); ``` -------------------------------- ### CLI: Transform CommonJS to ESM files Source: https://context7.com/wessberg/cjstoesm/llms.txt Use the cjstoesm command-line interface to transform CommonJS files to ES Modules. It supports glob patterns for input files, output directories, verbose logging, dry runs, and options to preserve module specifiers and control import attributes for JSON files. ```bash npm install -g cjstoesm # Transform all files in the src directory (overwrites in place) cjstoesm "src/**/*.*" # Transform files to a different output directory cjstoesm "src/**/*.*" dist # Transform a specific folder cjstoesm "src" # Run with verbose output cjstoesm "src/**/*.*" --verbose # Dry run (preview without writing) cjstoesm "src/**/*.*" --dry # Preserve external module specifiers (default behavior) cjstoesm "src/**/*.*" --preserve-module-specifiers external # Disable import attributes for JSON files cjstoesm "src/**/*.*" --import-attributes false # Run with npx without installing npx -p typescript -p cjstoesm cjstoesm "src/**/*.*" ``` -------------------------------- ### Transpile CommonJS to ESM using TypeScript transpileModule Source: https://github.com/wessberg/cjstoesm/blob/master/README.md Demonstrates the simplest way to use cjstoesm as a custom transformer with the TypeScript transpileModule API. It requires setting the module compiler option to ESNext. ```typescript import {ModuleKind, transpileModule} from "typescript"; import {cjsToEsm} from "cjstoesm"; const result = transpileModule(`const {join} = require("path");`, { transformers: cjsToEsm(), compilerOptions: { module: ModuleKind.ESNext } }); console.log(result.outputText); ``` -------------------------------- ### CJSTOESM: Conditional Require Conversion to Dynamic Imports Source: https://github.com/wessberg/cjstoesm/blob/master/README.md Explains that conditional require() syntax is not converted to dynamic imports due to the Promise-based nature of dynamic imports, which cannot directly replicate the synchronous behavior of require(). ```typescript const result = true ? require("./foo") : require("./bar"); ``` ```typescript import foo from "./foo.js"; import bar from "./bar.js"; const result = true ? foo : bar; ``` -------------------------------- ### Perform CLI transformations Source: https://github.com/wessberg/cjstoesm/blob/master/README.md Use the cjstoesm CLI to transform files from CommonJS to ESM. You can specify input globs, target directories, and various configuration flags. ```bash cjstoesm "**/*.*" cjstoesm "src" cjstoesm "**/*.*" dist cjstoesm --help ``` -------------------------------- ### Define TransformOptions interface Source: https://github.com/wessberg/cjstoesm/blob/master/README.md Configuration interface for the transform function, defining input globs, output directories, and transformation behavior settings. ```typescript interface TransformOptions { input: string[] | string; outDir?: string; write: boolean; fileSystem: FileSystem; logger: Loggable; cwd: string; preserveModuleSpecifiers: "always" | "never" | "external" | "internal" | ((specifier: string) => boolean); importAttributes: boolean | ((specifier: string) => boolean); typescript: typeof TS; debug: boolean | string | ((file: string) => boolean); } ``` -------------------------------- ### Programmatic API: Transform CommonJS files with JavaScript/TypeScript Source: https://context7.com/wessberg/cjstoesm/llms.txt The `transform` function provides a programmatic interface to convert CommonJS files to ES Modules. It accepts input file paths or glob patterns and an output directory. Options include disabling writing to disk (`write: false`), preserving module specifiers, enabling import attributes, and debugging. ```typescript import {transform} from "cjstoesm"; // Basic transformation - transforms files and writes to disk const result = await transform({ input: "src/**/*.*", outDir: "dist" }); console.log(`Transformed ${result.files.length} files`); // Transform without writing to disk const dryResult = await transform({ input: "src/**/*.js", write: false }); // Process transformed files manually for (const {fileName, text} of dryResult.files) { console.log(`File: ${fileName}`); console.log(text); } // Transform with custom options const customResult = await transform({ input: ["src/**/*.js", "lib/**/*.js"], outDir: "esm", preserveModuleSpecifiers: "external", // Keep external module specifiers unchanged importAttributes: true, // Add import attributes for JSON files debug: true // Enable debug logging }); ``` -------------------------------- ### Integrate cjstoesm with TypeScript Program API Source: https://github.com/wessberg/cjstoesm/blob/master/README.md Shows how to apply the cjstoesm transformer when emitting files from a full TypeScript Program instance. ```typescript import {getDefaultCompilerOptions, createProgram, createCompilerHost} from "typescript"; import {cjsToEsm} from "cjstoesm"; const options = getDefaultCompilerOptions(); const program = createProgram({ options, rootNames: ["my-file.js", "my-file.ts"], host: createCompilerHost(options) }); program.emit(undefined, undefined, undefined, undefined, cjsToEsm()); ``` -------------------------------- ### Transform CommonJS Exports to ESM Source: https://github.com/wessberg/cjstoesm/blob/master/README.md Demonstrates how cjstoesm converts CommonJS exports into named and default ES module exports. This ensures the resulting code is tree-shakeable and idiomatic. ```typescript // Input exports.foo = function foo() {}; // Output export function foo() {} ``` -------------------------------- ### Programmatic API transformation Source: https://github.com/wessberg/cjstoesm/blob/master/README.md Use the transform function to convert modules programmatically. This allows for either automatic file writing or manual handling of the transformation results. ```typescript import {transform} from "cjstoesm"; await transform({ input: "src/**/*.*", outDir: "dist" }); const result = await transform({ input: "src/**/*.*", write: false }); for (const {fileName, text} of result.files) { writeFileSync(fileName, text); } ``` -------------------------------- ### Configure cjstoesm with Rollup Source: https://github.com/wessberg/cjstoesm/blob/master/README.md Integrates cjstoesm into a Rollup build pipeline using @rollup/plugin-typescript by providing the transformer via the plugin options. ```javascript import ts from "@rollup/plugin-typescript"; import {cjsToEsm} from "cjstoesm"; export default { input: "...", plugins: [ ts({ transformers: program => cjsToEsm({program}) }) ] }; ``` -------------------------------- ### Transform Complex Module Exports Source: https://github.com/wessberg/cjstoesm/blob/master/README.md Shows the transformation of object-based module.exports into individual named exports and a default export. This maintains compatibility while enabling tree-shaking. ```typescript // Input module.exports = { foo() { return 2 + 2; }, bar: 3, baz: new RegExp("") }; // Output export function foo() { return 2 + 2; } export const bar = 3; export const baz = new RegExp(""); export default {foo, bar, baz}; ``` -------------------------------- ### Configure cjstoesm with Webpack Loaders Source: https://github.com/wessberg/cjstoesm/blob/master/README.md Configures cjstoesm as a custom transformer within Webpack using either awesome-typescript-loader or ts-loader. ```javascript import {cjsToEsm} from "cjstoesm"; const config = { module: { rules: [ { test: /(\.mjs)|(\.[jt]sx?)$/, loader: "awesome-typescript-loader", options: { getCustomTransformers: () => cjsToEsm() } } ] } }; ``` -------------------------------- ### Rollup Integration with @rollup/plugin-typescript Source: https://context7.com/wessberg/cjstoesm/llms.txt Integrate cjstoesm into a Rollup build process by using the `@rollup/plugin-typescript` plugin and providing the `cjsToEsm` transformer. This allows Rollup to process CommonJS modules as part of its ESM bundling. ```typescript // rollup.config.js import ts from "@rollup/plugin-typescript"; import {cjsToEsm} from "cjstoesm"; export default { input: "src/index.ts", output: [ { file: "dist/bundle.esm.js", format: "esm" } ], plugins: [ ts({ transformers: program => cjsToEsm({program}) }) ] }; ``` -------------------------------- ### Transform Require Calls to Import Statements Source: https://github.com/wessberg/cjstoesm/blob/master/README.md Converts CommonJS require statements into ES module import declarations. It handles destructuring and complex require chains to produce granular imports. ```typescript // Input const {foo: bar} = require("./my-module"); // Output import {foo as bar} from "./my-module.js"; ``` -------------------------------- ### Transformer Factory: cjsToEsmTransformerFactory() Source: https://context7.com/wessberg/cjstoesm/llms.txt Use `cjsToEsmTransformerFactory` to obtain a transformer that can be combined with other TypeScript transformers. This provides more control when integrating cjstoesm into complex build pipelines, such as those used by Rollup or Webpack. ```typescript import {ModuleKind, transpileModule} from "typescript"; import {cjsToEsmTransformerFactory} from "cjstoesm"; const result = transpileModule( `exports.foo = function foo() { return 42; }; exports.bar = 3;`, { transformers: { before: [cjsToEsmTransformerFactory(), /* other transformers */], after: [], afterDeclarations: [] }, compilerOptions: { module: ModuleKind.ESNext } } ); console.log(result.outputText); // Output: // export function foo() { return 42; } // export const bar = 3; ``` -------------------------------- ### TypeScript Custom Transformer: cjsToEsm() Source: https://context7.com/wessberg/cjstoesm/llms.txt The `cjsToEsm` function generates a TypeScript Custom Transformer object. This can be used with TypeScript's `transpileModule` or `program.emit` for integrating CommonJS to ESM transformation directly into TypeScript compilation workflows. ```typescript import {ModuleKind, transpileModule} from "typescript"; import {cjsToEsm} from "cjstoesm"; // Basic usage with transpileModule const result = transpileModule( `const {join} = require("path"); const fs = require("fs"); module.exports = { join, fs };`, { transformers: cjsToEsm(), compilerOptions: { module: ModuleKind.ESNext } } ); console.log(result.outputText); // Output: // import { join } from "path"; // import fs from "fs"; // export { join, fs }; // export default { join, fs }; // With a full TypeScript Program import {getDefaultCompilerOptions, createProgram, createCompilerHost} from "typescript"; const options = getDefaultCompilerOptions(); const program = createProgram({ options: {...options, module: ModuleKind.ESNext, allowJs: true}, rootNames: ["my-file.js", "my-other-file.ts"], host: createCompilerHost(options) }); program.emit(undefined, undefined, undefined, undefined, cjsToEsm()); ``` -------------------------------- ### Transform JSON Imports with Attributes Source: https://github.com/wessberg/cjstoesm/blob/master/README.md Automatically adds necessary import attributes, such as type: 'json', when importing JSON files from CommonJS require statements. ```typescript // Input const pkg = require("./package.json"); // Output import pkg from "./package.json" with {type: "json"}; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.