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-like-tsc.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"enhanced-resolve": patch
---

Resolve tsconfig `extends` the way tsc does, including package `exports`.
150 changes: 61 additions & 89 deletions lib/TsconfigPathsPlugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
const { aliasResolveHandler, compileAliasOptions } = require("./AliasUtils");
const { modulesResolveHandler } = require("./ModulesUtils");
const { readJson } = require("./util/fs");
const { PathType: _PathType, isSubPath, normalize } = require("./util/path");
const { PathType, getType, isSubPath } = require("./util/path");

/** @typedef {import("./Resolver")} Resolver */
/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */
Expand Down Expand Up @@ -67,6 +67,11 @@ const DEFAULT_CONFIG_FILE = "tsconfig.json";

const READ_JSON_OPTIONS = { stripComments: true };

const BACKSLASH_RE = /\\/g;

/** @type {WeakMap<Resolver, Resolver>} */
const extendsResolvers = new WeakMap();

// Trailing `/*` or `\*` segment of a tsconfig `paths` mapping (e.g.
// `./src/*` → `./src`). Hoisted so we don't allocate a fresh regex per
// path entry on every tsconfig load — and so the same regex object can be
Expand Down Expand Up @@ -607,26 +612,11 @@ module.exports = class TsconfigPathsPlugin {
visitedConfigPaths,
callback,
) {
const { fileSystem } = resolver;
const currentDir = resolver.dirname(configFilePath);

// Substitute ${configDir} in extends path
extendedConfigValue = substituteConfigDir(extendedConfigValue, currentDir);

// Remember the original value before potentially appending .json
const originalExtendedConfigValue = extendedConfigValue;

if (
typeof extendedConfigValue === "string" &&
!extendedConfigValue.includes(".json")
) {
extendedConfigValue += ".json";
}

const initialExtendedConfigPath = resolver.join(
currentDir,
const extendedConfig = substituteConfigDir(
extendedConfigValue,
);
currentDir,
).replace(BACKSLASH_RE, "/");

/**
* @param {string} extendedConfigPath resolved config path to load
Expand Down Expand Up @@ -661,81 +651,63 @@ module.exports = class TsconfigPathsPlugin {
);
};

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("/") &&
!originalExtendedConfigValue.startsWith(".") &&
!originalExtendedConfigValue.startsWith("/")
) {
// 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
* Load the value as a file path relative to the config, like tsc does.
* @returns {void}
*/
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);
const loadRelative = () => {
const extendedConfigPath = resolver.join(currentDir, extendedConfig);
if (extendedConfigPath.endsWith(".json")) {
return loadExtended(extendedConfigPath);
}
resolver.fileSystem.stat(extendedConfigPath, (err, stats) => {
loadExtended(
stats && stats.isFile()
? extendedConfigPath
: `${extendedConfigPath}.json`,
);
});
};

check(startDir);
const type = getType(extendedConfig);
// Like tsc, a "./", "../" or absolute value names a file, with ".json" as
// a fallback. Anything else, "." and ".." included, resolves like a
// `require` of a config: `exports`, the `tsconfig` field, tsconfig.json.
if (
type === PathType.AbsolutePosix ||
type === PathType.AbsoluteWin ||
extendedConfig.startsWith("./") ||
extendedConfig.startsWith("../")
) {
return loadRelative();
}

let extendsResolver = extendsResolvers.get(resolver);
if (extendsResolver === undefined) {
// Required lazily, since ResolverFactory requires this module.
extendsResolver = require("./ResolverFactory").createResolver({
fileSystem: resolver.fileSystem,
conditionNames: ["require", "types", "node"],
extensions: [".json"],
mainFields: ["tsconfig"],
mainFiles: ["tsconfig"],
});
extendsResolvers.set(resolver, extendsResolver);
}
// A trailing slash keeps "." and ".." directories, as in tsc, so a
// sibling "<dir>.json" never matches.
extendsResolver.resolve(
{},
currentDir,
type === PathType.Relative ? `${extendedConfig}/` : extendedConfig,
{},
(err, extendedConfigPath) => {
// tsc rejects a bare file name like "tsconfig.base.json", but it has
// always loaded from the config's directory here, so keep that.
if (err) return loadRelative();
loadExtended(/** @type {string} */ (extendedConfigPath));
},
);
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const util = "util";
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"compilerOptions": {
"paths": {
"@app/*": ["${configDir}/src/*"]
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "tsconfig.base.json"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"compilerOptions": {
"paths": {
"@app/*": ["${configDir}/src/*"]
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const util = "util";
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "./configs/base.tsconfig"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"compilerOptions": {
"paths": {
"@app/*": ["${configDir}/wrong/*"]
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const util = "util";
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": ".."
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"compilerOptions": {
"paths": {
"@app/*": ["${configDir}/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.

Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const util = "util";
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "base-config/strict"
}

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 @@
export const util = "util";
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "base-config"
}
38 changes: 38 additions & 0 deletions test/tsconfig-paths.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1838,4 +1838,42 @@ describe("TsconfigPathsPlugin", () => {
);
});
});

describe("extends resolution (#706)", () => {
const extendsResolutionDir = path.resolve(
__dirname,
"fixtures",
"tsconfig-paths",
"extends-resolution",
);

for (const [description, project] of [
["a package subpath mapped by `exports`", "pkg-exports"],
["the `tsconfig` field of a package", "pkg-tsconfig-field"],
["a relative file without a .json name", "non-json-name"],
["'..' as a directory, not a sibling '<dir>.json'", "parent-dir/app"],
["a bare file name, which tsc rejects", "bare-file-name"],
]) {
it(`should resolve paths inherited from ${description}`, (t, done) => {
const projectDir = path.join(extendsResolutionDir, project);
const resolver = ResolverFactory.createResolver({
fileSystem,
extensions: [".ts", ".tsx"],
mainFields: ["browser", "main"],
mainFiles: ["index"],
tsconfig: path.join(projectDir, "tsconfig.json"),
});

resolver.resolve({}, projectDir, "@app/util", {}, (err, result) => {
if (err) return done(err);
if (!result) return done(new Error("No result"));
assert.deepStrictEqual(
result,
path.join(projectDir, "src", "util.ts"),
);
done();
});
});
}
});
});
16 changes: 0 additions & 16 deletions types/TsconfigPathsPlugin.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,22 +86,6 @@ declare class TsconfigPathsPlugin {
visitedConfigPaths: Set<string>,
callback: (err: Error | null, result?: Tsconfig) => void,
): void;
/**
* 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: Resolver,
startDir: string,
subPath: string,
callback: (found: string | null) => void,
): void;
/**
* Load referenced tsconfig projects and store in referenceMatchMap
* Simple implementation matching tsconfig-paths-webpack-plugin:
Expand Down
Loading