Skip to content

Commit 385a946

Browse files
robhoganmeta-codesync[bot]
authored andcommitted
Resolver: Fix browser-spec bare-specifier->relative path redirect for nested/first-party package.jsons (#1720)
Summary: Pull Request resolved: #1720 The [browser spec](https://github.com/defunctzombie/package-browser-field-spec) redirect for bare specifiers (`"browser": {"foo-pkg": "./shims/foo.js"}`) was previously rebased against a path derived by slicing `originModulePath` after the last `node_modules/` segment. That happens to be correct only in the (common) case that the closest `package.json` is the one at the root of a containing `node_modules` package. However: - It's legal for an NPM package to contain nested `package.json` files and those may contain redirects - in which case their targets are relative to themselves, not to the package root `package.json`. - For origin modules that aren't located inside a `node_modules` tree (e.g. project-local source), `lastIndexOf('node_modules/')` returns `-1`, producing a malformed root path and either failed resolutions or surprising successes. This diff replaces that derivation with `closestPackageToOrigin.rootPath`, which we already look up at the top of `resolve`. Behaviour is identical in the already-working cases, and corrected otherwise. Matches webpack's `AliasFieldPlugin`, which rebases against `request.descriptionFileRoot`. Changelog: ``` - **[Fix]**: Fix browser-spec redirects of bare specifier to relative path, where `package.json` is not directly under `node_modules/<pkg>/` ```` Reviewed By: huntie Differential Revision: D105485945 fbshipit-source-id: 0b0b0b985294024d64305a15720ecc9007658d16
1 parent f3643cc commit 385a946

2 files changed

Lines changed: 64 additions & 13 deletions

File tree

‎packages/metro-resolver/src/__tests__/browser-spec-test.js‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,4 +99,61 @@ describe('browser field spec', () => {
9999
});
100100
});
101101
});
102+
103+
describe('replace specific files', () => {
104+
test('should resolve a bare-specifier redirect relative to the origin package root, not its containing directory', () => {
105+
// Per the browser spec, paths in the `browser` map are relative to the
106+
// package.json file location. When the origin module lives in a
107+
// subdirectory of its package (here `lib/nested/`), the redirect target
108+
// must still resolve against the package root.
109+
const packageJson = {
110+
name: 'origin-pkg',
111+
main: 'lib/nested/index.js',
112+
browser: {
113+
'foo-pkg': './shims/foo.js',
114+
},
115+
};
116+
const context = {
117+
...createResolutionContext({
118+
'/root/node_modules/origin-pkg/package.json':
119+
JSON.stringify(packageJson),
120+
'/root/node_modules/origin-pkg/lib/nested/index.js': '',
121+
'/root/node_modules/origin-pkg/shims/foo.js': '',
122+
}),
123+
originModulePath: '/root/node_modules/origin-pkg/lib/nested/index.js',
124+
mainFields: ['browser', 'main'],
125+
};
126+
127+
expect(Resolver.resolve(context, 'foo-pkg', null)).toEqual({
128+
type: 'sourceFile',
129+
filePath: '/root/node_modules/origin-pkg/shims/foo.js',
130+
});
131+
});
132+
133+
test('should resolve a bare-specifier redirect for an origin outside of `node_modules`', () => {
134+
// Project-level package.json — there is no enclosing `node_modules`
135+
// segment, so the old heuristic of slicing after `node_modules/` would
136+
// misbehave. The redirect must resolve against the package root.
137+
const context = {
138+
...createResolutionContext({
139+
'/root/project/package.json': JSON.stringify({
140+
name: 'project',
141+
main: 'src/index.js',
142+
browser: {
143+
'foo-pkg': './shims/foo.js',
144+
},
145+
}),
146+
'/root/project/src/index.js': '',
147+
'/root/project/shims/foo.js': '',
148+
}),
149+
originModulePath: '/root/project/src/index.js',
150+
mainFields: ['browser', 'main'],
151+
};
152+
153+
expect(Resolver.resolve(context, 'foo-pkg', null)).toEqual({
154+
type: 'sourceFile',
155+
filePath: '/root/project/shims/foo.js',
156+
});
157+
});
158+
});
102159
});

‎packages/metro-resolver/src/resolve.js‎

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -135,22 +135,16 @@ export default function resolve(
135135
// If the specifier was redirected to a relative path
136136
if (
137137
maybeRedirectedSpecifier != null &&
138+
closestPackageToOrigin != null && // Implied by maybeRedirectedSpecifier != null
138139
isRelativeImport(maybeRedirectedSpecifier)
139140
) {
140-
// TODO: (robhogan) This isn't right - per browser spec: "All paths for
141-
// browser fields are relative to the package.json file location". The
142-
// *closest* package.json is the relevant one for browser spec, regardless
143-
// of the closest node_modules.
144-
145-
// derive absolute path /.../node_modules/originModuleDir/specifier
146-
const fromModuleParentIdx =
147-
originModulePath.lastIndexOf('node_modules' + path.sep) + 13;
148-
const originModuleDir = originModulePath.slice(
149-
0,
150-
originModulePath.indexOf(path.sep, fromModuleParentIdx),
141+
// Per the "browser" spec: "All paths for browser fields are relative to
142+
// the package.json file location". `closestPackageToOrigin` is the package
143+
// that provided the redirect, so join relative paths to its `rootPath`.
144+
const absPath = path.resolve(
145+
closestPackageToOrigin.rootPath,
146+
maybeRedirectedSpecifier,
151147
);
152-
153-
const absPath = path.join(originModuleDir, maybeRedirectedSpecifier);
154148
const result = resolveModulePath(context, absPath, platform);
155149
if (result.type === 'failed') {
156150
throw new FailedToResolvePathError(result.candidates);

0 commit comments

Comments
 (0)