Skip to content

Commit a60c848

Browse files
author
Mariusz Pasinski
committed
feat: change the third param to original path
1 parent ee87dd0 commit a60c848

File tree

1 file changed

+9
-15
lines changed
  • packages/react-native-node-api-modules/src/node/babel-plugin

1 file changed

+9
-15
lines changed

packages/react-native-node-api-modules/src/node/babel-plugin/plugin.ts

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,8 @@ import path from "node:path";
33

44
import type { PluginObj, NodePath } from "@babel/core";
55
import * as t from "@babel/types";
6-
import { packageDirectorySync } from "pkg-dir";
7-
import { readPackageSync } from "read-pkg";
86

9-
import { isNodeApiModule } from "../path-utils";
7+
import { determineModuleContext, isNodeApiModule } from "../path-utils";
108

119
export type PluginOptions = {
1210
stripPathSuffix?: boolean;
@@ -78,17 +76,13 @@ function findNodeAddonForBindings(id: string, fromDir: string) {
7876
export function replaceWithRequireNodeAddon3(
7977
p: NodePath,
8078
resolvedPath: string,
79+
originalPath: string,
8180
requiredFrom: string
8281
) {
83-
const pkgRoot = packageDirectorySync({ cwd: resolvedPath });
84-
if (pkgRoot === undefined) {
85-
throw new Error("Unable to locate package directory!");
86-
}
87-
88-
const subpath = path.relative(pkgRoot, resolvedPath);
89-
const dottedSubpath = subpath.startsWith("./") ? subpath : `./${subpath}`;
90-
const fromRelative = path.relative(pkgRoot, requiredFrom); // TODO: might escape package
91-
const { name } = readPackageSync({ cwd: pkgRoot });
82+
const { packageName, relativePath } = determineModuleContext(resolvedPath);
83+
const finalRelPath = relativePath.startsWith("./")
84+
? relativePath
85+
: `./${relativePath}`;
9286

9387
p.replaceWith(
9488
t.callExpression(
@@ -98,7 +92,7 @@ export function replaceWithRequireNodeAddon3(
9892
]),
9993
t.identifier("requireNodeAddon")
10094
),
101-
[dottedSubpath, name, fromRelative]
95+
[finalRelPath, packageName, originalPath]
10296
.map(t.stringLiteral),
10397
)
10498
);
@@ -130,14 +124,14 @@ export function plugin(): PluginObj {
130124
const id = argument.value;
131125
const resolvedPath = findNodeAddonForBindings(id, from);
132126
if (resolvedPath !== undefined) {
133-
replaceWithRequireNodeAddon3(p.parentPath, resolvedPath, this.filename);
127+
replaceWithRequireNodeAddon3(p.parentPath, resolvedPath, id, this.filename);
134128
}
135129
}
136130
} else {
137131
// This should handle "bare specifiers" and "private imports" that start with `#`
138132
const resolvedPath = tryResolveModulePath(id, from);
139133
if (!!resolvedPath && isNodeApiModule(resolvedPath)) {
140-
replaceWithRequireNodeAddon3(p, resolvedPath, this.filename);
134+
replaceWithRequireNodeAddon3(p, resolvedPath, id, this.filename);
141135
}
142136
}
143137
}

0 commit comments

Comments
 (0)