Skip to content

Instantly share code, notes, and snippets.

@krutoo
Last active October 7, 2025 17:47
Show Gist options
  • Select an option

  • Save krutoo/70dd3068c9a0b8b1105da749bc475ede to your computer and use it in GitHub Desktop.

Select an option

Save krutoo/70dd3068c9a0b8b1105da749bc475ede to your computer and use it in GitHub Desktop.
Babel plugin for remove Node module resolution imports
import fs from 'node:fs';
import path from 'node:path';
const EXT = ['js', 'jsx', 'ts', 'tsx', '.cjs', '.mjs'];
export default function pluginNodeModuleResolution() {
return {
visitor: {
ImportOrExportDeclaration: {
enter(nodePath, { file }) {
// нет информации о файле - пропускаем
if (!file.opts.filename) {
return;
}
// у ExportDefaultDeclaration не может быть source - пропускаем
if (nodePath.node.type === 'ExportDefaultDeclaration') {
return;
}
// если нет source - пропускаем
if (!nodePath.node.source) {
return;
}
// если это не относительный и не абсолютный путь - пропускаем
if (
!nodePath.node.source.value.startsWith('.') &&
!nodePath.node.source.value.startsWith('/')
) {
return;
}
const targetAbsPath = path.resolve(
path.dirname(file.opts.filename),
nodePath.node.source.value,
);
if (!fs.existsSync(targetAbsPath)) {
for (const ext of EXT) {
const result = `${targetAbsPath}.${ext}`;
if (fs.existsSync(result) && fs.lstatSync(result).isFile()) {
nodePath.node.source.value = `${nodePath.node.source.value}${path.extname(result)}`;
return;
}
}
return;
}
const stats = fs.lstatSync(targetAbsPath);
// существующий файл без расширения - пропускаем
if (stats.isFile()) {
return;
}
// не директория - пропускаем
if (!stats.isDirectory()) {
return;
}
for (const ext of EXT) {
const result = path.resolve(targetAbsPath, `index.${ext}`);
if (fs.existsSync(result) && fs.lstatSync(result).isFile()) {
nodePath.node.source.value = `./${path.join(nodePath.node.source.value, `index.${ext}`)}`;
break;
}
}
},
},
},
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment