Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add support for jsconfig.json #199

Merged
merged 6 commits into from Apr 18, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Expand Up @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/).

## [Unreleased]

- Add support for `jsconfig.json`. See PR [#199](https://github.com/dividab/tsconfig-paths/pull/199). Thanks to [@F3n67u](https://github.com/F3n67u) for this PR!

## [3.14.1] - 2022-03-22

### Fixed
Expand Down
8 changes: 4 additions & 4 deletions README.md
Expand Up @@ -6,11 +6,11 @@
[![MIT license][license-image]][license-url]
[![code style: prettier][prettier-image]][prettier-url]

Use this to load modules whose location is specified in the `paths` section of `tsconfig.json`. Both loading at run-time and via API are supported.
Use this to load modules whose location is specified in the `paths` section of `tsconfig.json` or `jsconfig.json`. Both loading at run-time and via API are supported.

Typescript by default mimics the Node.js runtime resolution strategy of modules. But it also allows the use of [path mapping](https://www.typescriptlang.org/docs/handbook/module-resolution.html) which allows arbitrary module paths (that doesn't start with "/" or ".") to be specified and mapped to physical paths in the filesystem. The typescript compiler can resolve these paths from `tsconfig` so it will compile OK. But if you then try to execute the compiled files with node (or ts-node), it will only look in the `node_modules` folders all the way up to the root of the filesystem and thus will not find the modules specified by `paths` in `tsconfig`.

If you require this package's `tsconfig-paths/register` module it will read the `paths` from `tsconfig.json` and convert node's module loading calls into to physical file paths that node can load.
If you require this package's `tsconfig-paths/register` module it will read the `paths` from `tsconfig.json` or `jsconfig.json` and convert node's module loading calls into to physical file paths that node can load.

## How to install

Expand Down Expand Up @@ -156,7 +156,7 @@ export interface ExplicitParams {
export function register(explicitParams: ExplicitParams): () => void;
```

This function will patch the node's module loading so it will look for modules in paths specified by tsconfig.json.
This function will patch the node's module loading so it will look for modules in paths specified by `tsconfig.json` or `jsconfig.json`.
A function is returned for you to reinstate Node's original module loading.

### loadConfig
Expand All @@ -180,7 +180,7 @@ export interface ConfigLoaderFailResult {
}
```

This function loads the tsconfig.json. It will start searching from the specified `cwd` directory. Passing the tsconfig.json file directly instead of a directory also works.
This function loads the `tsconfig.json` or `jsconfig.json`. It will start searching from the specified `cwd` directory. Passing the `tsconfig.json` or `jsconfig.json` file directly instead of a directory also works.

### createMatchPath

Expand Down
52 changes: 46 additions & 6 deletions src/__tests__/tsconfig-loader.test.ts
Expand Up @@ -107,27 +107,67 @@ describe("tsconfig-loader", () => {
describe("walkForTsConfig", () => {
it("should find tsconfig in starting directory", () => {
const pathToTsconfig = join("/root", "dir1", "tsconfig.json");
const mockFiles: Record<string, string[]> = {
"/root/dir1": ["tsconfig.json"],
};
const res = walkForTsConfig(
join("/root", "dir1"),
(path) => mockFiles[path] || []
);
expect(res).toBe(pathToTsconfig);
});

it("should find jsconfig in starting directory", () => {
const pathToJsconfig = join("/root", "dir1", "jsconfig.json");
const mockFiles: Record<string, string[]> = {
"/root/dir1": ["jsconfig.json"],
};
const res = walkForTsConfig(
join("/root", "dir1"),
(path) => mockFiles[path] || []
);
expect(res).toBe(pathToJsconfig);
});

// see https://github.com/Microsoft/TypeScript/issues/15869#issuecomment-301845650
it("tsconfig.json take precedence over jsconfig.json when both exist", () => {
F3n67u marked this conversation as resolved.
Show resolved Hide resolved
const pathToTsconfig = join("/root/dir1", "tsconfig.json");
const mockFiles: Record<string, string[]> = {
"/root/dir1": ["jsconfig.json", "tsconfig.json"],
};
const res = walkForTsConfig(
join("/root", "dir1"),
(path) => path === pathToTsconfig
(path) => mockFiles[path] || []
);
// assert.equal(res, pathToTsconfig);
expect(res).toBe(pathToTsconfig);
});

it("should find tsconfig in parent directory", () => {
const pathToTsconfig = join("/root", "tsconfig.json");
const mockFiles: Record<string, string[]> = {
"/root": ["tsconfig.json"],
};
const res = walkForTsConfig(
join("/root", "dir1"),
(path) => mockFiles[path] || []
);
expect(res).toBe(pathToTsconfig);
});

it("should find jsconfig in parent directory", () => {
const pathToTsconfig = join("/root", "jsconfig.json");
const mockFiles: Record<string, string[]> = {
"/root": ["jsconfig.json"],
};
const res = walkForTsConfig(
join("/root", "dir1"),
(path) => path === pathToTsconfig
(path) => mockFiles[path] || []
);
// assert.equal(res, pathToTsconfig);
expect(res).toBe(pathToTsconfig);
});

it("should return undefined when reaching the top", () => {
const res = walkForTsConfig(join("/root", "dir1", "kalle"), () => false);
// assert.equal(res, undefined);
const res = walkForTsConfig(join("/root", "dir1", "kalle"), () => []);
expect(res).toBeUndefined();
});
});
Expand Down
17 changes: 9 additions & 8 deletions src/tsconfig-loader.ts
Expand Up @@ -90,25 +90,26 @@ function resolveConfigPath(cwd: string, filename?: string): string | undefined {
const configAbsolutePath = walkForTsConfig(cwd);
return configAbsolutePath ? path.resolve(configAbsolutePath) : undefined;
}

export function walkForTsConfig(
directory: string,
// eslint-disable-next-line no-shadow
existsSync: (path: string) => boolean = fs.existsSync
readdirSync: (path: string) => string[] = fs.readdirSync
): string | undefined {
const configPath = path.join(directory, "./tsconfig.json");
if (existsSync(configPath)) {
return configPath;
const files = readdirSync(directory);
const filesToCheck = ["tsconfig.json", "jsconfig.json"];
for (const fileToCheck of filesToCheck) {
if (files.indexOf(fileToCheck) !== -1) {
F3n67u marked this conversation as resolved.
Show resolved Hide resolved
return path.join(directory, fileToCheck);
}
}

const parentDirectory = path.join(directory, "../");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jonaskello Was there a good reason for using path.join instead of path.dirname here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • path.join('/root/dir', '../') return /root/
  • path.dirname('/root/dir') return /root(without the trailing directory separators)

the latter is normalized, easier to mock when we mock the fs.readdirSync, so I adjust path.join to path.dirname; though path.join(directory, '..') is fine either.

const parentDirectory = path.dirname(directory);

// If we reached the top
if (directory === parentDirectory) {
return undefined;
}

return walkForTsConfig(parentDirectory, existsSync);
return walkForTsConfig(parentDirectory, readdirSync);
}

export function loadTsconfig(
Expand Down