Security News
Weekly Downloads Now Available in npm Package Search Results
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
babel-plugin-transform-rewrite-imports
Advanced tools
Add an extension to import specifiers that do not already have one, replace the extensions of those that do, or even rewrite specifiers 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.
npm install --save-dev babel-plugin-transform-rewrite-imports
And 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 dist
The 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, static import()
, and
arbitrary dynamic import()
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.json
manually.
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.ts
files).
By mapping a project's tsconfig.json
paths
value to a replacement map
transform-rewrite-imports can understand, it becomes possible to ditch
tsconfig-replace-paths et al 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's
tsconfig.json
paths
into a replaceExtensions
replacement 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;
}
appendExtension
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 forappendExtension
. This means bare specifiers (e.g. built-in packages and packages imported fromnode_modules
) and absolute specifiers will never be affected byappendExtension
.
recognizedExtensions
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'] } ] ] };
replaceExtensions
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'
}
}
]
]
};
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.
requireLikeFunctions
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 CallExpression
s 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 namedefaultRequireLikeFunctions
.
This means call expressions like require(...)
, jest.mock(...)
, et al 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.
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 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 dist
With 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
xscripts'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 Node.js versions that are not end-of-life.
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, and a less complex build process.
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
declarations file for TypeScript and IDEs, an
exports[ENTRY].module
condition pointing to
(usually ESM) source for Webpack/Rollup, an exports[ENTRY].node
condition
pointing to (usually CJS2) source for Node.js require
and import
, an
exports[ENTRY].default
condition pointing to source for browsers and other
environments, and other conditions not enumerated
here. Check the package.json file to see which export
conditions are supported.
Though package.json
includes
{ "type": "commonjs" }
, note that any ESM-only entry points will
be ES module (.mjs
) files. Finally, package.json
also
includes the sideEffects
key, which is false
for
optimal tree shaking.
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! ✊🏿 Thank you!
See CONTRIBUTING.md and SUPPORT.md for more information.
Thanks goes to these wonderful people (emoji key):
Bernard 🚇 💻 📖 🚧 ⚠️ 👀 |
Add your contributions |
This project follows the all-contributors specification. Contributions of any kind welcome!
[1.5.3][3] (2024-10-30)
FAQs
Add an extension to import specifiers that do not already have one, replace the extensions of those that do, or even rewrite specifiers entirely.
The npm package babel-plugin-transform-rewrite-imports receives a total of 1,482 weekly downloads. As such, babel-plugin-transform-rewrite-imports popularity was classified as popular.
We found that babel-plugin-transform-rewrite-imports demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
Security News
A Stanford study reveals 9.5% of engineers contribute almost nothing, costing tech $90B annually, with remote work fueling the rise of "ghost engineers."
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.