Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/tsconfig-extends-node-modules-hoisting.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"enhanced-resolve": patch
---

Resolve tsconfig `extends` package specifiers from ancestor node_modules directories (workspace hoisting).
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ jobs:
rm -f package-lock.json
npm config set progress false
npm install -g npm@7
npm install -D jest@^27 memfs@^3 --ignore-scripts --no-audit --prefer-offline --no-save --no-package-lock
npm install -D jest@^27 memfs@^3 --ignore-scripts --no-audit --no-save --no-package-lock

- name: Install dependencies
if: matrix.node-version != '10.x' && matrix.node-version != '12.x' && matrix.node-version != '14.x' && matrix.node-version != '16.x'
Expand Down
117 changes: 76 additions & 41 deletions lib/TsconfigPathsPlugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -624,47 +624,10 @@ module.exports = class TsconfigPathsPlugin {
extendedConfigValue,
);

fileSystem.stat(initialExtendedConfigPath, (existsErr) => {
let extendedConfigPath = initialExtendedConfigPath;
if (existsErr) {
// Handle scoped package extends like "@scope/name" (no sub-path):
// "@scope/name" should resolve to node_modules/@scope/name/tsconfig.json,
// not node_modules/@scope/name.json
// See: test/fixtures/tsconfig-paths/extends-pkg-entry/
if (
typeof originalExtendedConfigValue === "string" &&
originalExtendedConfigValue.startsWith("@") &&
originalExtendedConfigValue.split("/").length === 2
) {
extendedConfigPath = resolver.join(
currentDir,
normalize(
`node_modules/${originalExtendedConfigValue}/${DEFAULT_CONFIG_FILE}`,
),
);
} else if (extendedConfigValue.includes("/")) {
// Handle package sub-path extends like "react/tsconfig":
// "react/tsconfig" resolves to node_modules/react/tsconfig.json
// See: test/fixtures/tsconfig-paths/extends-npm/
extendedConfigPath = resolver.join(
currentDir,
normalize(`node_modules/${extendedConfigValue}`),
);
} else if (
!originalExtendedConfigValue.startsWith(".") &&
!originalExtendedConfigValue.startsWith("/")
) {
// Handle unscoped package extends like "my-base-config" (no sub-path):
// "my-base-config" should resolve to node_modules/my-base-config/tsconfig.json
extendedConfigPath = resolver.join(
currentDir,
normalize(
`node_modules/${originalExtendedConfigValue}/${DEFAULT_CONFIG_FILE}`,
),
);
}
}

/**
* @param {string} extendedConfigPath resolved config path to load
*/
const loadExtended = (extendedConfigPath) => {
this._loadTsconfig(
resolver,
extendedConfigPath,
Expand Down Expand Up @@ -692,9 +655,81 @@ module.exports = class TsconfigPathsPlugin {
callback(null, cfg);
},
);
};

fileSystem.stat(initialExtendedConfigPath, (existsErr) => {
if (!existsErr) return loadExtended(initialExtendedConfigPath);

// The relative form does not exist — treat the value as a package
// specifier and compute its `node_modules/<...>` sub-path.
let nodeModulesSubPath = null;
if (
typeof originalExtendedConfigValue === "string" &&
originalExtendedConfigValue.startsWith("@") &&
originalExtendedConfigValue.split("/").length === 2
) {
// Scoped package, no sub-path ("@scope/name") →
// node_modules/@scope/name/tsconfig.json (not @scope/name.json).
// See: test/fixtures/tsconfig-paths/extends-pkg-entry/
nodeModulesSubPath = `${originalExtendedConfigValue}/${DEFAULT_CONFIG_FILE}`;
} else if (extendedConfigValue.includes("/")) {
// Package sub-path ("react/tsconfig", "@scope/name/tsconfig") →
// node_modules/react/tsconfig.json.
// See: test/fixtures/tsconfig-paths/extends-npm/
nodeModulesSubPath = extendedConfigValue;
} else if (
!originalExtendedConfigValue.startsWith(".") &&
!originalExtendedConfigValue.startsWith("/")
) {
// Unscoped package, no sub-path ("my-base-config") →
// node_modules/my-base-config/tsconfig.json.
nodeModulesSubPath = `${originalExtendedConfigValue}/${DEFAULT_CONFIG_FILE}`;
}

// Not a package specifier (relative/absolute) — load the missing
// path anyway so the read surfaces its own ENOENT.
if (nodeModulesSubPath === null) {
return loadExtended(initialExtendedConfigPath);
}

// Walk ancestor node_modules like Node.js/TypeScript so a package
// hoisted to a parent workspace directory is found. #21457
const subPath = normalize(`node_modules/${nodeModulesSubPath}`);
this._findExtendsInNodeModules(resolver, currentDir, subPath, (found) => {
loadExtended(found || resolver.join(currentDir, subPath));
});
});
}

/**
* Walk up from startDir looking for `<dir>/<subPath>` (a
* `node_modules/...` sub-path), matching Node.js module resolution so a
* package hoisted to a parent workspace's node_modules is found.
* @param {Resolver} resolver the resolver
* @param {string} startDir directory to start searching from
* @param {string} subPath node_modules-relative sub-path to look for
* @param {(found: string | null) => void} callback receives the found path or null
* @returns {void}
*/
_findExtendsInNodeModules(resolver, startDir, subPath, callback) {
const { fileSystem } = resolver;

/**
* @param {string} dir current directory
*/
const check = (dir) => {
const candidate = resolver.join(dir, subPath);
fileSystem.stat(candidate, (statErr) => {
if (!statErr) return callback(candidate);
const parentDir = resolver.dirname(dir);
if (parentDir === dir) return callback(null);
check(parentDir);
});
};

check(startDir);
}

/**
* Load referenced tsconfig projects and store in referenceMatchMap
* Simple implementation matching tsconfig-paths-webpack-plugin:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const y = "y";
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"extends": ".missing-base",
"compilerOptions": {
"paths": {
"@x/*": ["./src/*"]
}
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "@my-tsconfig/base/tsconfig.node"
}
60 changes: 60 additions & 0 deletions test/tsconfig-paths.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,12 @@ const extendsUnscopedPkgDir = path.resolve(
"tsconfig-paths",
"extends-unscoped-pkg",
);
const extendsNpmWorkspaceDir = path.resolve(
__dirname,
"fixtures",
"tsconfig-paths",
"extends-npm-workspace",
);

describe("TsconfigPathsPlugin", () => {
it("resolves exact mapped path '@components/*' via tsconfig option (example)", (t, done) => {
Expand Down Expand Up @@ -1643,4 +1649,58 @@ describe("TsconfigPathsPlugin", () => {
);
});
});

describe("extends a non-existent dot-prefixed value (not a package specifier)", () => {
const missingRelativeDir = path.resolve(
__dirname,
"fixtures",
"tsconfig-paths",
"extends-missing-relative",
);

it("surfaces the load error instead of searching node_modules", () => {
const resolver = ResolverFactory.createResolver({
fileSystem,
extensions: [".ts", ".tsx"],
mainFields: ["browser", "main"],
mainFiles: ["index"],
tsconfig: path.join(missingRelativeDir, "tsconfig.json"),
useSyncFileSystemCalls: true,
});

assert.throws(() => {
resolver.resolveSync({}, missingRelativeDir, "@x/y");
});
});
});

describe("bug: npm package in extends field hoisted to a parent node_modules (#21457)", () => {
it("should resolve a scoped package extends from a parent workspace node_modules", (t, done) => {
const appDir = path.join(extendsNpmWorkspaceDir, "packages", "app");
const resolver = ResolverFactory.createResolver({
fileSystem,
extensions: [".ts", ".tsx"],
mainFields: ["browser", "main"],
mainFiles: ["index"],
tsconfig: path.join(appDir, "tsconfig.json"),
});

resolver.resolve({}, appDir, "@pkg/util", {}, (err, result) => {
if (err) return done(err);
if (!result) return done(new Error("No result"));
assert.deepStrictEqual(
result,
path.join(
extendsNpmWorkspaceDir,
"node_modules",
"@my-tsconfig",
"base",
"src",
"util.ts",
),
);
done();
});
});
});
});