Rewrite Imports Utility

3.0.0 · active · verified Sun Apr 19

rewrite-imports is a lightweight (349B) utility designed to transform ECMAScript `import` statements into CommonJS `require()` calls using regular expressions. As of its current stable version, 3.0.0, it provides a performant way to transpile modules at the string level, without relying on an Abstract Syntax Tree (AST) parser. This makes it extremely fast and suitable for build-time processing in environments where a full AST transformation is overkill or undesired. The package typically sees minor updates and patches, with major versions introducing breaking changes like the shift to named exports in v3.0.0. Its primary differentiator is its simplicity and reliance on RegExp, offering a niche solution for projects that need a quick, no-frills import rewriting mechanism, particularly for older Node.js environments (>=6) or browser environments with a `require` shim. Unlike full module bundlers or transpilers, it solely performs string replacement and does not provide a runtime or evaluate the transformed code.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to use the `rewrite` function to convert various ES import syntaxes into CommonJS require() statements.

import { rewrite } from 'rewrite-imports';

// Example 1: Default import
console.log(rewrite(`import foo from '../bar'`));
// Expected output: const foo = require('../bar');

// Example 2: Named import
console.log(rewrite(`import { foo } from 'bar'`));
// Expected output: const { foo } = require('bar');

// Example 3: Namespace import
console.log(rewrite(`import * as path from 'path';`));
// Expected output: const path = require('path');

// Example 4: Renamed named imports
console.log(rewrite(`import { foo as bar, baz as bat, lol } from 'quz';`));
// Expected output: const { foo:bar, baz:bat, lol } = require('quz');

// Example 5: Mixed default and named imports
console.log(rewrite(`import foobar, { foo as FOO, bar } from 'foobar';`));
// Expected output:
// const foobar = require('foobar');
// const { foo:FOO, bar } = foobar;

view raw JSON →