Skip to content

Commit

Permalink
feat: implement a resolver that supports exports (#209)
Browse files Browse the repository at this point in the history
  • Loading branch information
SukkaW authored Dec 19, 2024
1 parent 449738f commit 46d2360
Show file tree
Hide file tree
Showing 6 changed files with 177 additions and 2 deletions.
52 changes: 52 additions & 0 deletions .changeset/witty-garlics-destroy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
---
"eslint-plugin-import-x": minor
---

When `eslint-plugin-import-x` was forked from `eslint-plugin-import`, we copied over the default resolver (which is `eslint-import-resolver-node`) as well. However, this resolver doesn't supports `exports` in the `package.json` file, and the current maintainer of the `eslint-import-resolver-node` (ljharb) doesn't have the time implementing this feature and he locked the issue https://github.com/import-js/eslint-plugin-import/issues/1810.

So we decided to implement our own resolver that "just works". The new resolver is built upon the [`enhanced-resolve`](https://www.npmjs.com/package/enhanced-resolve) that implements the full Node.js [Resolver Algorithm](https://nodejs.org/dist/v14.21.3/docs/api/esm.html#esm_resolver_algorithm). The new resolver only implements the import resolver interface v3, which means you can only use it with ESLint Flat config. For more details about the import resolver interface v3, please check out [#192](https://github.com/un-ts/eslint-plugin-import-x/pull/192).

In the next major version of `eslint-plugin-import-x`, we will remove the `eslint-import-resolver-node` and use this new resolver by default. In the meantime, you can try out this new resolver by setting the `import-x/resolver-next` option in your `eslint.config.js` file:

```js
// eslint.config.js
const eslintPluginImportX = require('eslint-plugin-import-x');
const { createNodeResolver } = eslintPluginImportX;

module.exports = {
plugins: {
'import-x': eslintPluginImportX,
},
settings: {
'import-x/resolver-next': [
// This is the new resolver we are introducing
createNodeResolver({
/**
* The allowed extensions the resolver will attempt to find when resolving a module
* By default it uses a relaxed extension list to search for both ESM and CJS modules
* You can customize this list to fit your needs
*
* @default ['.mjs', '.cjs', '.js', '.json', '.node']
*/
extensions?: string[];
/**
* Optional, the import conditions the resolver will used when reading the exports map from "package.json"
* By default it uses a relaxed condition list to search for both ESM and CJS modules
* You can customize this list to fit your needs
*
* @default ['default', 'module', 'import', 'require']
*/
conditions: ['default', 'module', 'import', 'require'],
// You can pass more options here, see the enhanced-resolve documentation for more details
// https://github.com/webpack/enhanced-resolve/tree/v5.17.1?tab=readme-ov-file#resolver-options
}),
// you can add more resolvers down below
require('eslint-import-resolver-typescript').createTypeScriptImportResolver(
/** options of eslint-import-resolver-typescript */
)
],
},
};
```

We do not plan to implement reading `baseUrl` and `paths` from the `tsconfig.json` file in this resolver. If you need this feature, please checkout [eslint-import-resolver-typescript](https://www.npmjs.com/package/eslint-import-resolver-typescript) (also powered by `enhanced-resolve`), [eslint-import-resolver-oxc](https://www.npmjs.com/package/eslint-import-resolver-oxc) (powered by `oxc-resolver`), [eslint-import-resolver-next](https://www.npmjs.com/package/eslint-import-resolver-next) (also powered by `oxc-resolver`), or other similar resolvers.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@
"@typescript-eslint/rule-tester": "^8.15.0",
"@unts/patch-package": "^8.0.0",
"cross-env": "^7.0.3",
"enhanced-resolve": "^5.16.0",
"enhanced-resolve": "^5.17.1",
"escope": "^4.0.0",
"eslint": "^9.15.0",
"eslint-config-prettier": "^9.1.0",
Expand Down
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ import type {
PluginFlatConfig,
} from './types'
import { importXResolverCompat } from './utils'
import { createNodeResolver } from './node-resolver'

Check failure on line 75 in src/index.ts

View workflow job for this annotation

GitHub Actions / Lint and Test with Node.js 20 and ESLint 8 on ubuntu-latest

`./node-resolver` import should occur before import of `./rules/consistent-type-specifier-style`

Check failure on line 75 in src/index.ts

View workflow job for this annotation

GitHub Actions / Lint and Test with Node.js 20 and ESLint 8.56 on ubuntu-latest

`./node-resolver` import should occur before import of `./rules/consistent-type-specifier-style`

Check failure on line 75 in src/index.ts

View workflow job for this annotation

GitHub Actions / Lint and Test with Node.js 20 and ESLint 9 on ubuntu-latest

`./node-resolver` import should occur before import of `./rules/consistent-type-specifier-style`

const rules = {
'no-unresolved': noUnresolved,
Expand Down Expand Up @@ -183,4 +184,5 @@ export = {
flatConfigs,
rules,
importXResolverCompat,
createNodeResolver

Check failure on line 187 in src/index.ts

View workflow job for this annotation

GitHub Actions / Lint and Test with Node.js 20 and ESLint 8 on ubuntu-latest

Insert `,`

Check failure on line 187 in src/index.ts

View workflow job for this annotation

GitHub Actions / Lint and Test with Node.js 20 and ESLint 8.56 on ubuntu-latest

Insert `,`

Check failure on line 187 in src/index.ts

View workflow job for this annotation

GitHub Actions / Lint and Test with Node.js 20 and ESLint 9 on ubuntu-latest

Insert `,`
}
68 changes: 68 additions & 0 deletions src/node-resolver.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { ResolverFactory, CachedInputFileSystem, type ResolveOptions } from 'enhanced-resolve';

Check failure on line 1 in src/node-resolver.ts

View workflow job for this annotation

GitHub Actions / Lint and Test with Node.js 20 and ESLint 8 on ubuntu-latest

'enhanced-resolve' should be listed in the project's dependencies, not devDependencies

Check failure on line 1 in src/node-resolver.ts

View workflow job for this annotation

GitHub Actions / Lint and Test with Node.js 20 and ESLint 8 on ubuntu-latest

There should be at least one empty line between import groups

Check failure on line 1 in src/node-resolver.ts

View workflow job for this annotation

GitHub Actions / Lint and Test with Node.js 20 and ESLint 8 on ubuntu-latest

`enhanced-resolve` import should occur after import of `node:path`

Check failure on line 1 in src/node-resolver.ts

View workflow job for this annotation

GitHub Actions / Lint and Test with Node.js 20 and ESLint 8 on ubuntu-latest

Replace `·ResolverFactory,·CachedInputFileSystem,·type·ResolveOptions·}·from·'enhanced-resolve';` with `⏎··ResolverFactory,⏎··CachedInputFileSystem,⏎··type·ResolveOptions,⏎}·from·'enhanced-resolve'`

Check failure on line 1 in src/node-resolver.ts

View workflow job for this annotation

GitHub Actions / Lint and Test with Node.js 20 and ESLint 8 on ubuntu-latest

Prefer using a top-level type-only import instead of inline type specifiers

Check failure on line 1 in src/node-resolver.ts

View workflow job for this annotation

GitHub Actions / Lint and Test with Node.js 20 and ESLint 8.56 on ubuntu-latest

'enhanced-resolve' should be listed in the project's dependencies, not devDependencies

Check failure on line 1 in src/node-resolver.ts

View workflow job for this annotation

GitHub Actions / Lint and Test with Node.js 20 and ESLint 8.56 on ubuntu-latest

There should be at least one empty line between import groups

Check failure on line 1 in src/node-resolver.ts

View workflow job for this annotation

GitHub Actions / Lint and Test with Node.js 20 and ESLint 8.56 on ubuntu-latest

`enhanced-resolve` import should occur after import of `node:path`

Check failure on line 1 in src/node-resolver.ts

View workflow job for this annotation

GitHub Actions / Lint and Test with Node.js 20 and ESLint 8.56 on ubuntu-latest

Replace `·ResolverFactory,·CachedInputFileSystem,·type·ResolveOptions·}·from·'enhanced-resolve';` with `⏎··ResolverFactory,⏎··CachedInputFileSystem,⏎··type·ResolveOptions,⏎}·from·'enhanced-resolve'`

Check failure on line 1 in src/node-resolver.ts

View workflow job for this annotation

GitHub Actions / Lint and Test with Node.js 20 and ESLint 8.56 on ubuntu-latest

Prefer using a top-level type-only import instead of inline type specifiers

Check failure on line 1 in src/node-resolver.ts

View workflow job for this annotation

GitHub Actions / Lint and Test with Node.js 20 and ESLint 9 on ubuntu-latest

'enhanced-resolve' should be listed in the project's dependencies, not devDependencies

Check failure on line 1 in src/node-resolver.ts

View workflow job for this annotation

GitHub Actions / Lint and Test with Node.js 20 and ESLint 9 on ubuntu-latest

There should be at least one empty line between import groups

Check failure on line 1 in src/node-resolver.ts

View workflow job for this annotation

GitHub Actions / Lint and Test with Node.js 20 and ESLint 9 on ubuntu-latest

`enhanced-resolve` import should occur after import of `node:path`

Check failure on line 1 in src/node-resolver.ts

View workflow job for this annotation

GitHub Actions / Lint and Test with Node.js 20 and ESLint 9 on ubuntu-latest

Replace `·ResolverFactory,·CachedInputFileSystem,·type·ResolveOptions·}·from·'enhanced-resolve';` with `⏎··ResolverFactory,⏎··CachedInputFileSystem,⏎··type·ResolveOptions,⏎}·from·'enhanced-resolve'`

Check failure on line 1 in src/node-resolver.ts

View workflow job for this annotation

GitHub Actions / Lint and Test with Node.js 20 and ESLint 9 on ubuntu-latest

Prefer using a top-level type-only import instead of inline type specifiers
import fs from 'node:fs';

Check failure on line 2 in src/node-resolver.ts

View workflow job for this annotation

GitHub Actions / Lint and Test with Node.js 20 and ESLint 8 on ubuntu-latest

There should be at least one empty line between import groups

Check failure on line 2 in src/node-resolver.ts

View workflow job for this annotation

GitHub Actions / Lint and Test with Node.js 20 and ESLint 8 on ubuntu-latest

Delete `;`

Check failure on line 2 in src/node-resolver.ts

View workflow job for this annotation

GitHub Actions / Lint and Test with Node.js 20 and ESLint 8.56 on ubuntu-latest

There should be at least one empty line between import groups

Check failure on line 2 in src/node-resolver.ts

View workflow job for this annotation

GitHub Actions / Lint and Test with Node.js 20 and ESLint 8.56 on ubuntu-latest

Delete `;`

Check failure on line 2 in src/node-resolver.ts

View workflow job for this annotation

GitHub Actions / Lint and Test with Node.js 20 and ESLint 9 on ubuntu-latest

There should be at least one empty line between import groups

Check failure on line 2 in src/node-resolver.ts

View workflow job for this annotation

GitHub Actions / Lint and Test with Node.js 20 and ESLint 9 on ubuntu-latest

Delete `;`
import type { NewResolver } from './types';

Check failure on line 3 in src/node-resolver.ts

View workflow job for this annotation

GitHub Actions / Lint and Test with Node.js 20 and ESLint 8 on ubuntu-latest

There should be at least one empty line between import groups

Check failure on line 3 in src/node-resolver.ts

View workflow job for this annotation

GitHub Actions / Lint and Test with Node.js 20 and ESLint 8.56 on ubuntu-latest

There should be at least one empty line between import groups

Check failure on line 3 in src/node-resolver.ts

View workflow job for this annotation

GitHub Actions / Lint and Test with Node.js 20 and ESLint 9 on ubuntu-latest

There should be at least one empty line between import groups
import { isBuiltin } from 'node:module';
import { dirname } from 'node:path';

interface NodeResolverOptions extends Omit<ResolveOptions, 'useSyncFileSystemCalls'> {
/**
* The allowed extensions the resolver will attempt to find when resolving a module
* @type {string[] | undefined}
* @default ['.mjs', '.cjs', '.js', '.json', '.node']
*/
extensions?: string[];
/**
* The import conditions the resolver will used when reading the exports map from "package.json"
* @type {string[] | undefined}
* @default ['default', 'module', 'import', 'require']
*/
conditionNames?: string[];
}

export function createNodeResolver({
extensions = ['.mjs', '.cjs', '.js', '.json', '.node'],
conditionNames = ['default', 'module', 'import', 'require'],
mainFields = ['main'],
exportsFields = ['exports'],
mainFiles = ['index'],
fileSystem = new CachedInputFileSystem(fs, 4 * 1000),
...restOptions
}: Partial<NodeResolverOptions> = {}): NewResolver {
const resolver = ResolverFactory.createResolver({
extensions,
fileSystem,
conditionNames,
useSyncFileSystemCalls: true,
...restOptions,
});

// shared context across all resolve calls

return {
interfaceVersion: 3,
name: 'eslint-plugin-import-x built-in node resolver',
resolve: (modulePath, sourceFile) => {
if (isBuiltin(modulePath)) {
return { found: true, path: null };
}

if (modulePath.startsWith('data:')) {
return { found: true, path: null };
}

try {
const path = resolver.resolveSync(
{},
dirname(sourceFile),
modulePath
);
if (path) {
return { found: true, path };
}
return { found: false };
} catch {
return { found: false };
}
}
}
}
45 changes: 45 additions & 0 deletions test/node-resolver.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import path from 'node:path'
import { cwd } from 'node:process'
import { createNodeResolver } from '../src/node-resolver';

const resolver = createNodeResolver()

function expectResolve(source: string, expected: boolean | string) {
it(`${source} => ${expected}`, () => {
try {
console.log({ source, expected, requireResolve: require.resolve(source, { paths: [__dirname] }) })

} catch {
console.log({ source, expected, requireResolve: null })
}
const result = resolver.resolve(source, __filename);
console.log({ source, expected, result })

if (typeof expected === 'string') {
expect(result.path).toBe(path.resolve(cwd(), expected))
} else {
expect(result.found).toBe(expected)
}
})
}

describe('builtin', () => {
expectResolve('path', true)
expectResolve('node:path', true)
})

describe('modules', () => {
expectResolve('jest', true)
expectResolve('@sukka/does-not-exists', false)
})

describe('relative', () => {
expectResolve('../package.json', 'package.json')
expectResolve('../.github/dependabot.yml', false)
expectResolve('../babel.config.js', 'babel.config.js')
expectResolve('../test/index.js', 'test/index.js')
expectResolve('../test/', 'test/index.js')
expectResolve('../test', 'test/index.js')

expectResolve('../inexistent.js', false)
})
10 changes: 9 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3413,14 +3413,22 @@ enhanced-resolve@^0.9.1:
memory-fs "^0.2.0"
tapable "^0.1.8"

enhanced-resolve@^5.12.0, enhanced-resolve@^5.16.0:
enhanced-resolve@^5.12.0:
version "5.16.0"
resolved "https://registry.yarnpkg.com/enhanced-resolve/-/enhanced-resolve-5.16.0.tgz#65ec88778083056cb32487faa9aef82ed0864787"
integrity sha512-O+QWCviPNSSLAD9Ucn8Awv+poAkqn3T1XY5/N7kR7rQO9yfSGWkYZDwpJ+iKF7B8rxaQKWngSqACpgzeapSyoA==
dependencies:
graceful-fs "^4.2.4"
tapable "^2.2.0"

enhanced-resolve@^5.17.1:
version "5.17.1"
resolved "https://registry.yarnpkg.com/enhanced-resolve/-/enhanced-resolve-5.17.1.tgz#67bfbbcc2f81d511be77d686a90267ef7f898a15"
integrity sha512-LMHl3dXhTcfv8gM4kEzIUeTQ+7fpdA0l2tUf34BddXPkz2A5xJ5L/Pchd5BL6rdccM9QGvu0sWZzK1Z1t4wwyg==
dependencies:
graceful-fs "^4.2.4"
tapable "^2.2.0"

enquirer@^2.3.0:
version "2.4.1"
resolved "https://registry.yarnpkg.com/enquirer/-/enquirer-2.4.1.tgz#93334b3fbd74fc7097b224ab4a8fb7e40bf4ae56"
Expand Down

0 comments on commit 46d2360

Please sign in to comment.