Reliably add/replace extensions of select import specifiers or just rewrite them entirely!
This Babel plugin (1) reliably adds extensions to import and export specifiers that do not already have one, (2) selectively replaces extensions of specifiers that do, and (3) can rewrite whole specifiers in intricate ways using simple yet powerful replacement maps.
All TypeScript and JavaScript flavors are supported depending on how Babel is configured in the project.
For example, something like this:
import { item1, type item2 } from '==> pretty specifier #1 <==';
export { here as there } from '==> pretty specifier #2 <==';
const elsewhere = `==> pretty specifier #${getRandomNumber()} <==`;
jest.mock('==> pretty specifier #3 <==');
const x = require('==> pretty specifier #4 <==');
export async function myFunction() {
return (await import(elsewhere, { with: { type: 'json' } })).name;
}
export type MyType = {
typeOnlyImport: typeof import('==> pretty specifier #5 <==').Type;
};Can be easily transformed into something like this:
import { item1, type item2 } from '../../../specifier-1.js';
export { here as there } from '../specifier-2.js';
const elsewhere = `==> specifier #${getRandomNumber()} <==`;
jest.mock('../../../packages/a-different-monorepo-package/src/specifier-3.js');
const x = require('@specifier/four');
const __injected_dynamic_rewrite = function () {
/*...*/
};
export async function myFunction() {
return (
await import(__injected_dynamic_rewrite(elsewhere), {
with: { type: 'json' }
})
).name;
}
export type MyType = {
typeOnlyImport: typeof import('../../../../node_modules/s-5/dist/src/lib.d.ts').Type;
};The transform-rewrite-imports plugin comes in handy in situations like
transpiling TypeScript source with extensionless imports to ESM, or changing
alias paths in TypeScript declaration (i.e. .d.ts) files into relative
paths suitable for publishing. It does this more reliably and efficiently than
prior art.
- Install
- Comparison with Prior Art
- Usage
- Advanced Usage
- Comprehensive Logging
- Examples
- Appendix
- Contributing and Support
npm install --save-dev babel-plugin-transform-rewrite-importsAnd integrate the following snippet into your Babel configuration:
module.exports = {
plugins: [
[
'babel-plugin-transform-rewrite-imports',
{
// See below for configuration instructions and examples
}
]
]
};Finally, run Babel through your toolchain (Webpack, Jest, etc) or manually:
npx babel src --out-dir distThe transform-rewrite-imports plugin effectively combines the functionality of the following:
-
The module-resolver plugin inspired quite a bit of the functionality of transform-rewrite-imports, such as transforming
require-like functions, and offers some similar features like RegExp-based aliasing and support for substitution functions. However, transform-rewrite-imports is capable of more complex replacements (like handling intricate file extension changes) with support for a wider variety of specifier types while surfacing a simpler interface. -
babel-plugin-add-import-extension
transform-rewrite-imports started off as a fork of add-import-extension; transform-rewrite-imports functions more consistently and includes support for transforming
require,require-like, staticimport(), and arbitrary dynamicimport()statements, replacing multiple extensions using complex logic, and reliably ignoring extensions that should not be replaced. -
babel-plugin-replace-import-extension
transform-rewrite-imports is similar in intent to replace-import-extension. However, rewriting extensions is only a small fraction of what transform-rewrite-imports can do. And while both extensions support transforming dynamic imports, transform-rewrite-imports results in more efficient code in production environments due to (1) avoiding injecting dynamic code into the AST except as the very last resort and (2) only injecting dynamic code once and caching it globally (at the file level) rather than filling the file with repeated functions.
-
babel-plugin-transform-rename-import
With its last update published over 6 years ago, transform-rename-import can also replace import specifiers, though transform-rewrite-imports offers a powerful superset of replacer functionality, including optionally performing replacements of arbitrary dynamic imports at runtime and appending extensions to specifiers that would otherwise not have one.
-
tsconfig-replace-paths / tsconfig-paths / tscpaths
tsconfig-replace-paths and its predecessors/alternatives tsconfig-paths and tscpaths are extremely useful for transpiling TypeScript projects, as they handle alias- and path- resolving use cases without additional configuration; transform-rewrite-imports, on the other hand, must be fed path/alias information from
tsconfig.jsonmanually.Unfortunately, tsconfig-paths is not a Babel plugin and requires patching your runtime while the others do not support all the latest TypeScript/Babel AST features (like
TsImportType) and therefore fail to consistently and correctly transform certain files (especially certain.d.tsfiles).By mapping a project's
tsconfig.jsonpathsvalue to a replacement map transform-rewrite-imports can understand, it becomes possible to ditch tsconfig-replace-paths etc and reduce dependency count. Here's an example using transform-rewrite-imports to replace these plugins (and babel-plugin-module-resolver) for transforming both sources and type definitions. Essentially, this Babel configuration file maps the project'stsconfig.jsonpathsinto areplaceExtensionsreplacement map.
By default this plugin does not affect Babel's output. You must explicitly configure this extension before any specifier will be rewritten.
More information on the available options can be found in the docs:
{
appendExtension?: string | Callback<string | undefined>;
recognizedExtensions?: string[];
replaceExtensions?: Record<string, string | Callback<string>>;
requireLikeFunctions?: string[];
injectDynamicRewriter?: 'never' | 'only-if-necessary';
silent?: boolean;
verbose?: boolean;
}To append an extension to all relative import specifiers that do not already
have a recognized extension, use appendExtension:
module.exports = {
plugins: [
[
'babel-plugin-transform-rewrite-imports',
{
appendExtension: '.mjs'
}
]
]
};Tip
Only relative import specifiers (that start with ./ or ../) will be
considered for appendExtension. This means bare specifiers (e.g. built-in
packages and packages imported from node_modules) and absolute specifiers
will never be affected by appendExtension.
What is and is not considered a "recognized extension" is determined by
recognizedExtensions:
module.exports = {
plugins: [
[
'babel-plugin-transform-rewrite-imports',
{
appendExtension: '.mjs',
recognizedExtensions: ['.js']
}
]
]
};That is: import specifiers that end with an extension included in
recognizedExtensions will never have appendExtension appended to
them. All other imports, including those with a . in the file name (e.g.
component.module.style.ts), may be rewritten.
recognizedExtensions is set to ['.js', '.jsx', '.mjs', '.cjs', '.json'] by
default.
If the value of appendExtension is not included in
recognizedExtensions, then imports that already end in appendExtension
will have appendExtension appended to them (e.g. index.ts is rewritten
as index.ts.ts when appendExtension: '.ts' and recognizedExtensions is its
default value). If this behavior is undesired, ensure appendExtension is
included in recognizedExtensions.
Warning
Note that specifying a custom value for recognizedExtensions overwrites the
default value entirely. To extend rather than overwrite, you can import the
default value from the package itself:
const {
defaultRecognizedExtensions
} = require('babel-plugin-transform-rewrite-imports');
module.exports = {
plugins: [
[
'babel-plugin-transform-rewrite-imports',
{
appendExtension: '.mjs',
recognizedExtensions: [...defaultRecognizedExtensions, '.ts']
}
]
]
};You can also replace one or more existing extensions in specifiers using a replacement map:
module.exports = {
plugins: [
[
'babel-plugin-transform-rewrite-imports',
{
replaceExtensions: {
// Replacements are evaluated **in order**, stopping on the first match.
// That means if the following two keys were listed in reverse order,
// .node.js would become .node.mjs instead of .cjs
'.node.js': '.cjs',
'.js': '.mjs'
}
}
]
]
};These configurations can be combined to rewrite many imports at once. For instance, if you wanted to replace certain extensions and append only when no recognized or listed extension is specified:
module.exports = {
plugins: [
[
'babel-plugin-transform-rewrite-imports',
{
appendExtension: '.mjs',
replaceExtensions: {
'.node.js': '.cjs',
// Since .js is in recognizedExtensions by default, file.js would normally
// be ignored. However, since .js is mapped to .mjs in the
// replaceExtensions map, file.js becomes file.mjs
'.js': '.mjs'
}
}
]
]
};Since specifier comparisons are made using String.endsWith without
splitting on directory separators or any other characters,
appendExtension and replaceExtensions accept any suffix, not just
those that begin with .; additionally, replaceExtensions accepts regular
expressions. This allows you to partially or entirely rewrite a specifier
rather than just its extension:
const {
defaultRecognizedExtensions
} = require('babel-plugin-transform-rewrite-imports');
module.exports = {
plugins: [
[
'babel-plugin-transform-rewrite-imports',
{
appendExtension: '.mjs',
// Add .css to recognizedExtensions so .mjs isn't automatically appended
recognizedExtensions: [...defaultRecognizedExtensions, '.css'],
replaceExtensions: {
'.node.js': '.cjs',
'.js': '.mjs',
// The following key replaces the entire specifier when matched
'^package$': `${__dirname}/package.json`,
// If .css wasn't in recognizedExtensions, my-utils/src/file.less would
// become my-utils/src/file.css.mjs instead of my-utils/src/file.css
'(.+?)\\.less$': '$1.css'
}
}
]
]
};Tip
If a key of replaceExtensions begins with ^ or ends with $, it is
considered a regular expression instead of an extension. Regular expression
replacements support substitutions of capturing groups as well (e.g. $1,
$2, etc).
replaceExtensions is evaluated and replacements made before
appendExtension is appended to specifiers with unrecognized or missing
extensions. This means an extensionless import specifier could be rewritten by
replaceExtensions to have a recognized extension, which would then be ignored
instead of having appendExtension appended to it.
When it comes to deciding what is and is not a specifier,
transform-rewrite-imports will always scan ImportDeclaration,
ExportAllDeclaration, ExportNamedDeclaration,
TSImportType, and dynamic import CallExpressions for specifiers.
For call expressions specifically, requireLikeFunctions is used to determine
which additional function calls will have their first arguments scanned for
specifiers. By default, requireLikeFunctions is set to:
[
'require',
'require.resolve',
'System.import',
'jest.genMockFromModule',
'jest.mock',
'jest.unmock',
'jest.doMock',
'jest.dontMock',
'jest.requireActual'
];Tip
Similar to defaultRequireLikeFunctions, these defaults are exported under
the name defaultRequireLikeFunctions.
This means call expressions like require(...), jest.mock(...), etc will be
treated the same way as import(...), where the first parameter is considered a
specifier. You are free to tweak this functionality to suit your environment.
By default, a dynamic rewriter is injected only if necessary. Set this to
"never" to ensure a dynamic rewriter is never injected into the the output
regardless of any perceived necessity.
Refer to the Advanced Usage section for more details.
replaceExtensions and appendExtension both accept function
callbacks as values everywhere strings are accepted. This can be used to provide
advanced replacement logic.
These callback functions have the following signatures:
type AppendExtensionCallback = (context: {
specifier: string;
capturingGroups: never[];
filepath: string;
}) => string | undefined;
type ReplaceExtensionsCallback = (context: {
specifier: string;
capturingGroups: string[];
filepath: string;
}) => string;Where specifier is the import/export specifier being rewritten,
capturingGroups is a simple string array of capturing groups returned by
String.prototype.match(), and filepath is the absolute path to the
original input file being transformed by Babel. capturingGroups will always be
an empty array except when it appears within a function value of a
replaceExtensions entry that has a regular expression key.
When provided as the value of appendExtension, a string containing an
extension should be returned (including leading dot). When provided as the value
of a replaceExtensions entry, a string containing the full specifier
should be returned. When returning a full specifier, capturing group
substitutions (e.g. $1, $2, etc) within the returned string will be honored.
Further, in the case of appendExtension, note that specifier, if its
basename is . or .. or if it ends in a directory separator (e.g. /), will
have "/index" appended to the end before the callback is invoked. However, if
the callback returns undefined (and the specifier was not matched in
replaceExtensions), the specifier will not be modified in any way.
By way of example (see the output of this example here):
module.exports = {
plugins: [
[
'babel-plugin-transform-rewrite-imports',
{
// If the specifier ends with "/no-ext", do not append any extension
appendExtension: ({ specifier }) => {
return specifier.endsWith('/no-ext') ||
specifier.endsWith('..') ||
specifier === './another-thing'
? undefined
: '.mjs';
},
replaceExtensions: {
// Rewrite imports of packages in a monorepo to use their actual names
// v capturing group #1: capturingGroups[1]
'^packages/([^/]+)(/.+)?': ({ specifier, capturingGroups }) => {
// ^ capturing group #2: capturingGroups[2]
if (
specifier === 'packages/root' ||
specifier.startsWith('packages/root/')
) {
return `./monorepo-js${capturingGroups[2] ?? '/'}`;
} else if (
!capturingGroups[2] ||
capturingGroups[2].startsWith('/src/index')
) {
return `@monorepo/$1`;
} else if (capturingGroups[2].startsWith('/package.json')) {
return `@monorepo/$1$2`;
} else {
return `@monorepo/$1/dist$2`;
}
}
}
}
]
]
};When transforming dynamic imports and require statements that do not have a
string literal as the first argument, and injectDynamicRewriter is
not set to 'never', the options passed to this plugin are transpiled and
injected into the resulting AST.
Caution
This means you take a slight performance hit when you do arbitrary dynamic
imports that cannot be statically analyzed (e.g.
require(getMd5Hash() + '.txt')). These types of dynamic imports are usually
code smell, but this library is built to accommodate them regardless.
However, if you are NOT doing arbitrary dynamic imports, which are dynamic imports where the first argument is not a string literal, then this section is of no relevance to you since nothing extra will be injected into the AST.
Therefore, to be safe, callback functions must not reference variables outside of their immediate scope.
Good:
module.exports = {
plugins: [
[
'babel-plugin-transform-rewrite-imports',
{
replaceExtensions: {
'^packages/([^/]+)(/.+)?': ({ specifier, capturingGroups }) => {
const myPkg = require('my-pkg');
myPkg.doStuff(specifier, capturingGroups);
}
}
}
]
]
};Bad:
const myPkg = require('my-pkg');
module.exports = {
plugins: [
[
'babel-plugin-transform-rewrite-imports',
{
replaceExtensions: {
'^packages/([^/]+)(/.+)?': ({ specifier, capturingGroups }) => {
myPkg.doStuff(specifier, capturingGroups);
}
}
}
]
]
};Technically, you can get away with violating this rule if you're sure you'll only ever use dynamic imports/require statements with string literal arguments.
Like Babel itself, this plugin leverages debug (via rejoinder) under the hood for log management. You can take advantage of this to peer into transform-rewrite-imports's innermost workings and deepest decision-making processes by activating the appropriate log level. For example, the following will enable all logging related to this plugin:
DEBUG='babel-plugin-transform-rewrite-imports:*' npx babel src --out-dir distWith the following snippet integrated into your Babel configuration:
const {
defaultRecognizedExtensions
} = require('babel-plugin-transform-rewrite-imports');
module.exports = {
plugins: [
[
'babel-plugin-transform-rewrite-imports',
{
appendExtension: '.mjs',
recognizedExtensions: [...defaultRecognizedExtensions, '.css'],
replaceExtensions: {
'.ts': '.mjs',
'^package$': `${__dirname}/package.json`,
'(.+?)\\.less$': '$1.css'
}
}
]
]
};The following source:
/* file: src/index.ts */
import { name as pkgName } from 'package';
import { primary } from '.';
import { secondary } from '..';
import { tertiary } from '../..';
import dirImport from './some-dir/';
import jsConfig from './jsconfig.json';
import projectConfig from './project.config.cjs';
import { add, double } from './src/numbers';
import { curry } from './src/typed/curry.ts';
import styles from './src/less/styles.less';
// Note that, unless otherwise configured, @babel/preset-typescript deletes
// type-only imports. If you want to operate on type imports and/or .d.ts files,
// use @babel/syntax-typescript instead. See ./test/supports-type-only for
// an example.
import type * as AllTypes from './lib/something.mjs';
export { triple, quadruple } from './lib/num-utils';
// Note that, unless otherwise configured, @babel/preset-typescript deletes
// type-only exports. If you want to operate on type imports and/or .d.ts files,
// use @babel/syntax-typescript instead. See ./test/supports-type-only for
// an example.
export type { NamedType } from './lib/something';
const thing = await import('./thing');
const anotherThing = require('./another-thing');
const thing2 = await import(someFn(`./${someVariable}`) + '.json');
const anotherThing2 = require(someOtherVariable);Is, depending on your other plugins/settings, transformed into something like:
/* file: dist/index.js */
const _rewrite = (importPath, options) => {
...
},
_rewrite_options = {
appendExtension: '.mjs',
recognizedExtensions: ['.js', '.jsx', '.mjs', '.cjs', '.json', '.css'],
replaceExtensions: {
'.ts': '.mjs',
'^package$': '/absolute/path/to/project/package.json',
'(.+?)\\.less$': '$1.css'
}
};
import { name as pkgName } from '/absolute/path/to/project/package.json';
import { primary } from './index.mjs';
import { secondary } from '../index.mjs';
import { tertiary } from '../../index.mjs';
import dirImport from './some-dir/index.mjs';
import jsConfig from './jsconfig.json';
import projectConfig from './project.config.cjs';
import { add, double } from './src/numbers.mjs';
import { curry } from './src/typed/curry.mjs';
import styles from './src/less/styles.css';
export { triple, quadruple } from './lib/num-utils.mjs';
const thing = await import('./thing.mjs');
const anotherThing = require('./another-thing.mjs');
// Require calls and dynamic imports with a non-string-literal first argument
// are transformed into function calls that dynamically return the rewritten
// string:
const thing2 = await import(
_rewrite(someFn(`./${someVariable}`) + '.json', _rewrite_options)
);
const anotherThing2 = require(_rewrite(someOtherVariable, _rewrite_options));Note
See the full output of this example here.
For some real-world examples of this Babel plugin in action, check out
symbiote's babel.config.js file (which uses transform-rewrite-imports to
replace both babel-plugin-module-resolver and tsconfig-replace-paths),
unified-utils, this very repository, or just take a peek at the
test cases.
Further documentation can be found under docs/.
This is a CJS2 package with statically-analyzable exports
built by Babel for use in Node.js versions that are not end-of-life. For
TypeScript users, this package supports both "Node10" and "Node16" module
resolution strategies.
Expand details
That means both CJS2 (via require(...)) and ESM (via import { ... } from ...
or await import(...)) source will load this package from the same entry points
when using Node. This has several benefits, the foremost being: less code
shipped/smaller package size, avoiding dual package
hazard entirely, distributables are not
packed/bundled/uglified, a drastically less complex build process, and CJS
consumers aren't shafted.
Each entry point (i.e. ENTRY) in package.json's
exports[ENTRY] object includes one or more export
conditions. These entries may or may not include: an
exports[ENTRY].types condition pointing to a type
declaration file for TypeScript and IDEs, a
exports[ENTRY].module condition pointing to
(usually ESM) source for Webpack/Rollup, a exports[ENTRY].node and/or
exports[ENTRY].default condition pointing to (usually CJS2) source for Node.js
require/import and for browsers and other environments, and other
conditions not enumerated here. Check the
package.json file to see which export conditions are
supported.
Note that, regardless of the { "type": "..." } specified in
package.json, any JavaScript files written in ESM
syntax (including distributables) will always have the .mjs extension. Note
also that package.json may include the
sideEffects key, which is almost always false for
optimal tree shaking where appropriate.
See LICENSE.
New issues and pull requests are always welcome and greatly appreciated! 🤩 Just as well, you can star 🌟 this project to let me know you found it useful! ✊🏿 Or buy me a beer, I'd appreciate it. Thank you!
See CONTRIBUTING.md and SUPPORT.md for more information.
Thanks goes to these wonderful people (emoji key):
Bernard 🚇 💻 📖 🚧 |
||||||
|
|
||||||
This project follows the all-contributors specification. Contributions of any kind welcome!
