Skip to content

Commit 1ee96b1

Browse files
committed
refactor and small fixes
1 parent 474eb6d commit 1ee96b1

File tree

7 files changed

+166
-88
lines changed

7 files changed

+166
-88
lines changed

config/jest/babelTransform.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ module.exports = {
1010
process(sourceText, sourcePath, options) {
1111
const alias = options?.config?.moduleNameMapper;
1212
const extensions = normalizeExtensions(options.config.moduleFileExtensions, options?.config?.haste?.defaultPlatform);
13-
const modulesDirs = options.config.moduleDirectories;
13+
const modulesDirs = [...options.config.moduleDirectories, ...(options.config.modulePaths || [])];
1414
const babelTransformer = babelJest.createTransformer({
1515
presets: [["@babel/preset-react"], ["@babel/preset-env"]],
1616
plugins: [["transform-barrels", { executorName: "jest", alias: alias, extensions: extensions, modulesDirs: modulesDirs }]],

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "babel-plugin-transform-barrels",
3-
"version": "1.0.21",
3+
"version": "1.0.22",
44
"description": "A Babel plugin that transforms indirect imports through a barrel file (index.js) into direct imports.",
55
"homepage": "https://github.com/FogelAI/babel-plugin-transform-barrels",
66
"main": "src/main.js",

src/path.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,7 @@ class PathFunctions {
5151
}
5252

5353
static isRelativePath(path) {
54-
const relativePathRegExp = /^\.{1,2}\//;
55-
return relativePathRegExp.test(path);
54+
return path.startsWith(".");
5655
}
5756

5857
static isRegularPath(path) {

src/resolver.js

Lines changed: 105 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ const { packageManager } = require("./packages");
55
let instance;
66
const defaultModulesDirs = ["node_modules"];
77
const defaultExtensions = ["", ".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs"];
8+
const nodeModulesFolder = {};
89

910
class Resolver {
1011
constructor() {
@@ -19,6 +20,7 @@ class Resolver {
1920
this.aliasObj = {};
2021
this.from = "";
2122
this.modulesDirs = defaultModulesDirs;
23+
this.absModuleDirs = [];
2224
this.extensions = defaultExtensions;
2325
}
2426

@@ -28,52 +30,91 @@ class Resolver {
2830
}
2931

3032
setModulesDirs(modulesDirs) {
31-
this.modulesDirs = modulesDirs;
33+
this.modulesDirs = [];
34+
for (const moduleDir of modulesDirs) {
35+
if (ospath.isAbsolute(moduleDir)) {
36+
this.absModuleDirs.push(moduleDir);
37+
} else {
38+
this.modulesDirs.push(moduleDir);
39+
}
40+
}
3241
}
3342

34-
isExtensionFile(path, ext) {
35-
const extFilePathRegex = new RegExp(`\.(${ext})$`);
36-
return extFilePathRegex.test(path.toLowerCase());
43+
resolve(path, from) {
44+
let resolvedPath;
45+
const fromDir = ospath.dirname(from);
46+
const originalPath = PathFunctions.isRegularPath(path) ? path : this.convertAliasToOriginal(path);
47+
resolvedPath = this.resolveRegularPaths(originalPath, fromDir);
48+
if (resolvedPath) return resolvedPath;
49+
resolvedPath = this.resolveAbsoluteModuleDirs(originalPath, fromDir);
50+
if (resolvedPath) return resolvedPath;
51+
return this.resolveNodeModules(originalPath, fromDir);
52+
}
53+
54+
resolveRegularPaths(path, fromDir) {
55+
let fixedPath = path;
56+
if (PathFunctions.isRelativePath(path)) {
57+
fixedPath = ospath.join(fromDir, path);
58+
}
59+
if (ospath.isAbsolute(fixedPath)) {
60+
return this.resolveAbsFilePath(fixedPath, fromDir);
61+
}
3762
}
3863

39-
getTargetPathType(target, from) {
40-
if (this.isExtensionFile(target, "cjs") || (!PathFunctions.isNodeModule(from) && PathFunctions.isNodeModule(target) && !this.isExtensionFile(target, "mjs"))) {
41-
return "CJS";
42-
} else {
43-
return "ESM";
64+
resolveAbsoluteModuleDirs(absPath, fromDir) {
65+
for (const absModuleDir of this.absModuleDirs) {
66+
const path = ospath.join(absModuleDir, absPath);
67+
const resolvedPath = this.resolveAbsFilePath(path, fromDir);
68+
if (resolvedPath) return resolvedPath;
4469
}
4570
}
4671

47-
resolve(path, from) {
48-
const originalPath = PathFunctions.isRegularPath(path) ? path : this.convertAliasToOriginal(path);
49-
const fromDir = ospath.dirname(from);
50-
const absolutePath = PathFunctions.getAbsolutePath(originalPath, fromDir, this.modulesDirs);
51-
if (!absolutePath) return;
52-
const filePath = this.getFilePathWithExtension(absolutePath);
53-
if (filePath) {
54-
const resolvedPath = new ResolvedPath();
55-
if (this.getTargetPathType(filePath, from) === "ESM") {
56-
resolvedPath.absEsmFile = filePath;
72+
resolveNodeModules(path, fromDir=process.cwd()) {
73+
let currentDir = fromDir;
74+
let mainPackage = path.split("/")[0];
75+
if (nodeModulesFolder[mainPackage] !== undefined) {
76+
if (nodeModulesFolder[mainPackage] === null) {
77+
return null;
5778
} else {
58-
resolvedPath.absCjsFile = filePath;
79+
const absPath = ospath.join(nodeModulesFolder[mainPackage], path);
80+
return this.resolveAbsFilePath(absPath, fromDir);
5981
}
60-
resolvedPath.originalPath = path;
61-
return resolvedPath;
62-
}
63-
const entryPath = this.getFilePathFromPackageJson(absolutePath, originalPath);
64-
if (entryPath) return entryPath;
65-
const indexPath = this.getIndexFilePath(absolutePath);
66-
if (indexPath) {
67-
const resolvedPath = new ResolvedPath();
68-
if (this.getTargetPathType(indexPath, from) === "ESM") {
69-
resolvedPath.absEsmFile = indexPath;
70-
} else {
71-
resolvedPath.absCjsFile = indexPath;
82+
}
83+
while (currentDir) {
84+
if (currentDir.endsWith("node_modules")) {
85+
currentDir = PathFunctions.removeLastSegment(currentDir);
86+
continue;
7287
}
73-
resolvedPath.originalPath = path;
74-
return resolvedPath;
75-
};
76-
}
88+
for (const modulesDir of this.modulesDirs) {
89+
const nodeModulesPath = ospath.join(currentDir, modulesDir);
90+
const absPath = ospath.join(nodeModulesPath, path);
91+
const resolvedPath = this.resolveAbsFilePath(absPath, fromDir);
92+
if (resolvedPath) {
93+
nodeModulesFolder[mainPackage] = nodeModulesPath;
94+
return resolvedPath;
95+
}
96+
}
97+
currentDir = PathFunctions.removeLastSegment(currentDir);
98+
}
99+
nodeModulesFolder[mainPackage] = null;
100+
return null;
101+
}
102+
103+
resolveAbsFilePath(absolutePath, fromDir) {
104+
const filePath = this.getFilePathWithExtension(absolutePath);
105+
if (filePath) {
106+
const resolvedDualPath = ResolvedPath.createDualResolvedPath(filePath, fromDir, absolutePath);
107+
return resolvedDualPath;
108+
}
109+
const normalizedModulePath = PathFunctions.normalizeModulePath(absolutePath)
110+
const entryPath = this.getFilePathFromPackageJson(absolutePath, normalizedModulePath);
111+
if (entryPath) return entryPath;
112+
const indexPath = this.getIndexFilePath(absolutePath);
113+
if (indexPath) {
114+
const resolvedDualPath = ResolvedPath.createDualResolvedPath(indexPath, fromDir, absolutePath);
115+
return resolvedDualPath;
116+
};
117+
}
77118

78119
getFilePathWithExtension(path) {
79120
const ext = this.extensions.find((ext)=> PathFunctions.fileExists(path + ext));
@@ -93,11 +134,10 @@ class Resolver {
93134
const esmModule = exportsObj?.absEsmFile || (type === "module" ? main : module);
94135
const absCjsModule = cjsModule && ospath.join(path, cjsModule);
95136
const absEsmModule = esmModule && ospath.join(path, esmModule);
96-
const resolvedPath = new ResolvedPath();
97-
resolvedPath.absCjsFile = absCjsModule ? this.getFilePathWithExtension(absCjsModule) : ""
98-
resolvedPath.absEsmFile = absEsmModule ? this.getFilePathWithExtension(absEsmModule) : ""
99-
resolvedPath.packageJsonExports = !!exportsObj;
100-
resolvedPath.originalPath = importPath;
137+
const absCjsModuleWithExt = absCjsModule ? this.getFilePathWithExtension(absCjsModule) : "";
138+
const absEsmModuleWithExt = absEsmModule ? this.getFilePathWithExtension(absEsmModule) : "";
139+
const packageJsonExports = !!exportsObj;
140+
const resolvedPath = new ResolvedPath(importPath, absEsmModuleWithExt, absCjsModuleWithExt, packageJsonExports);
101141
return resolvedPath;
102142
}
103143
}
@@ -129,6 +169,30 @@ class Resolver {
129169
}
130170

131171
class ResolvedPath {
172+
static isExtensionFile(path, ext) {
173+
const extFilePathRegex = new RegExp(`\.(${ext})$`);
174+
return extFilePathRegex.test(path.toLowerCase());
175+
}
176+
177+
static getTargetPathType(target, from) {
178+
if (ResolvedPath.isExtensionFile(target, "cjs") || (!PathFunctions.isNodeModule(from) && PathFunctions.isNodeModule(target) && !ResolvedPath.isExtensionFile(target, "mjs"))) {
179+
return "CJS";
180+
} else {
181+
return "ESM";
182+
}
183+
}
184+
185+
static createDualResolvedPath(filePath, from, absolutePath) {
186+
const resolvedDualPath = new ResolvedPath();
187+
if (ResolvedPath.getTargetPathType(filePath, from) === "ESM") {
188+
resolvedDualPath.absEsmFile = filePath;
189+
} else {
190+
resolvedDualPath.absCjsFile = filePath;
191+
}
192+
resolvedDualPath.originalPath = PathFunctions.normalizeModulePath(absolutePath);
193+
return resolvedDualPath;
194+
}
195+
132196
constructor(originalPath, absEsmFile, absCjsFile, packageJsonExports) {
133197
this.originalPath = originalPath || "";
134198
this.absEsmFile = absEsmFile || "";

tests/js/local/imports.test.js

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ describe("aliases", () => {
140140

141141
test("transformation of jest alias", () => {
142142
const alias = Object.entries({
143-
"^abc/(.*)$": "./components/$1"
143+
"^abc/(.*)$": ospath.resolve(__dirname, "./components/$1")
144144
});
145145
const pluginOptions = { executorName: "jest", alias: alias };
146146
expect(
@@ -209,6 +209,18 @@ describe("modules directories", () => {
209209
)
210210
).toBe(`import { RedText as NamedExported } from \"${ospath.resolve(__dirname)}\\components\\Texts\\RedText\\RedText.js";`.replaceAll("\\","\\\\"));
211211
});
212+
213+
test("resolve module file - absolute path", () => {
214+
const modulesDirs = [ospath.resolve(__dirname), 'node_modules'];
215+
const pluginOptions = { executorName: "webpack", modulesDirs: modulesDirs };
216+
expect(
217+
pluginTransform(
218+
'import { logger } from "logger";',
219+
__filename,
220+
pluginOptions
221+
)
222+
).toBe(`import { logger } from \"logger\";`);
223+
});
212224
});
213225

214226
describe("special module usecases transformation", () => {

tests/js/local/logger.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export const logger = "logger";

0 commit comments

Comments
 (0)