Skip to content

Commit 46d2360

Browse files
authored
feat: implement a resolver that supports exports (#209)
1 parent 449738f commit 46d2360

File tree

6 files changed

+177
-2
lines changed

6 files changed

+177
-2
lines changed

.changeset/witty-garlics-destroy.md

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
---
2+
"eslint-plugin-import-x": minor
3+
---
4+
5+
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.
6+
7+
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).
8+
9+
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:
10+
11+
```js
12+
// eslint.config.js
13+
const eslintPluginImportX = require('eslint-plugin-import-x');
14+
const { createNodeResolver } = eslintPluginImportX;
15+
16+
module.exports = {
17+
plugins: {
18+
'import-x': eslintPluginImportX,
19+
},
20+
settings: {
21+
'import-x/resolver-next': [
22+
// This is the new resolver we are introducing
23+
createNodeResolver({
24+
/**
25+
* The allowed extensions the resolver will attempt to find when resolving a module
26+
* By default it uses a relaxed extension list to search for both ESM and CJS modules
27+
* You can customize this list to fit your needs
28+
*
29+
* @default ['.mjs', '.cjs', '.js', '.json', '.node']
30+
*/
31+
extensions?: string[];
32+
/**
33+
* Optional, the import conditions the resolver will used when reading the exports map from "package.json"
34+
* By default it uses a relaxed condition list to search for both ESM and CJS modules
35+
* You can customize this list to fit your needs
36+
*
37+
* @default ['default', 'module', 'import', 'require']
38+
*/
39+
conditions: ['default', 'module', 'import', 'require'],
40+
// You can pass more options here, see the enhanced-resolve documentation for more details
41+
// https://github.com/webpack/enhanced-resolve/tree/v5.17.1?tab=readme-ov-file#resolver-options
42+
}),
43+
// you can add more resolvers down below
44+
require('eslint-import-resolver-typescript').createTypeScriptImportResolver(
45+
/** options of eslint-import-resolver-typescript */
46+
)
47+
],
48+
},
49+
};
50+
```
51+
52+
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.

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@
9696
"@typescript-eslint/rule-tester": "^8.15.0",
9797
"@unts/patch-package": "^8.0.0",
9898
"cross-env": "^7.0.3",
99-
"enhanced-resolve": "^5.16.0",
99+
"enhanced-resolve": "^5.17.1",
100100
"escope": "^4.0.0",
101101
"eslint": "^9.15.0",
102102
"eslint-config-prettier": "^9.1.0",

src/index.ts

+2
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ import type {
7272
PluginFlatConfig,
7373
} from './types'
7474
import { importXResolverCompat } from './utils'
75+
import { createNodeResolver } from './node-resolver'
7576

7677
const rules = {
7778
'no-unresolved': noUnresolved,
@@ -183,4 +184,5 @@ export = {
183184
flatConfigs,
184185
rules,
185186
importXResolverCompat,
187+
createNodeResolver
186188
}

src/node-resolver.ts

+68
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import { ResolverFactory, CachedInputFileSystem, type ResolveOptions } from 'enhanced-resolve';
2+
import fs from 'node:fs';
3+
import type { NewResolver } from './types';
4+
import { isBuiltin } from 'node:module';
5+
import { dirname } from 'node:path';
6+
7+
interface NodeResolverOptions extends Omit<ResolveOptions, 'useSyncFileSystemCalls'> {
8+
/**
9+
* The allowed extensions the resolver will attempt to find when resolving a module
10+
* @type {string[] | undefined}
11+
* @default ['.mjs', '.cjs', '.js', '.json', '.node']
12+
*/
13+
extensions?: string[];
14+
/**
15+
* The import conditions the resolver will used when reading the exports map from "package.json"
16+
* @type {string[] | undefined}
17+
* @default ['default', 'module', 'import', 'require']
18+
*/
19+
conditionNames?: string[];
20+
}
21+
22+
export function createNodeResolver({
23+
extensions = ['.mjs', '.cjs', '.js', '.json', '.node'],
24+
conditionNames = ['default', 'module', 'import', 'require'],
25+
mainFields = ['main'],
26+
exportsFields = ['exports'],
27+
mainFiles = ['index'],
28+
fileSystem = new CachedInputFileSystem(fs, 4 * 1000),
29+
...restOptions
30+
}: Partial<NodeResolverOptions> = {}): NewResolver {
31+
const resolver = ResolverFactory.createResolver({
32+
extensions,
33+
fileSystem,
34+
conditionNames,
35+
useSyncFileSystemCalls: true,
36+
...restOptions,
37+
});
38+
39+
// shared context across all resolve calls
40+
41+
return {
42+
interfaceVersion: 3,
43+
name: 'eslint-plugin-import-x built-in node resolver',
44+
resolve: (modulePath, sourceFile) => {
45+
if (isBuiltin(modulePath)) {
46+
return { found: true, path: null };
47+
}
48+
49+
if (modulePath.startsWith('data:')) {
50+
return { found: true, path: null };
51+
}
52+
53+
try {
54+
const path = resolver.resolveSync(
55+
{},
56+
dirname(sourceFile),
57+
modulePath
58+
);
59+
if (path) {
60+
return { found: true, path };
61+
}
62+
return { found: false };
63+
} catch {
64+
return { found: false };
65+
}
66+
}
67+
}
68+
}

test/node-resolver.spec.ts

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import path from 'node:path'
2+
import { cwd } from 'node:process'
3+
import { createNodeResolver } from '../src/node-resolver';
4+
5+
const resolver = createNodeResolver()
6+
7+
function expectResolve(source: string, expected: boolean | string) {
8+
it(`${source} => ${expected}`, () => {
9+
try {
10+
console.log({ source, expected, requireResolve: require.resolve(source, { paths: [__dirname] }) })
11+
12+
} catch {
13+
console.log({ source, expected, requireResolve: null })
14+
}
15+
const result = resolver.resolve(source, __filename);
16+
console.log({ source, expected, result })
17+
18+
if (typeof expected === 'string') {
19+
expect(result.path).toBe(path.resolve(cwd(), expected))
20+
} else {
21+
expect(result.found).toBe(expected)
22+
}
23+
})
24+
}
25+
26+
describe('builtin', () => {
27+
expectResolve('path', true)
28+
expectResolve('node:path', true)
29+
})
30+
31+
describe('modules', () => {
32+
expectResolve('jest', true)
33+
expectResolve('@sukka/does-not-exists', false)
34+
})
35+
36+
describe('relative', () => {
37+
expectResolve('../package.json', 'package.json')
38+
expectResolve('../.github/dependabot.yml', false)
39+
expectResolve('../babel.config.js', 'babel.config.js')
40+
expectResolve('../test/index.js', 'test/index.js')
41+
expectResolve('../test/', 'test/index.js')
42+
expectResolve('../test', 'test/index.js')
43+
44+
expectResolve('../inexistent.js', false)
45+
})

yarn.lock

+9-1
Original file line numberDiff line numberDiff line change
@@ -3413,14 +3413,22 @@ enhanced-resolve@^0.9.1:
34133413
memory-fs "^0.2.0"
34143414
tapable "^0.1.8"
34153415

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

3424+
enhanced-resolve@^5.17.1:
3425+
version "5.17.1"
3426+
resolved "https://registry.yarnpkg.com/enhanced-resolve/-/enhanced-resolve-5.17.1.tgz#67bfbbcc2f81d511be77d686a90267ef7f898a15"
3427+
integrity sha512-LMHl3dXhTcfv8gM4kEzIUeTQ+7fpdA0l2tUf34BddXPkz2A5xJ5L/Pchd5BL6rdccM9QGvu0sWZzK1Z1t4wwyg==
3428+
dependencies:
3429+
graceful-fs "^4.2.4"
3430+
tapable "^2.2.0"
3431+
34243432
enquirer@^2.3.0:
34253433
version "2.4.1"
34263434
resolved "https://registry.yarnpkg.com/enquirer/-/enquirer-2.4.1.tgz#93334b3fbd74fc7097b224ab4a8fb7e40bf4ae56"

0 commit comments

Comments
 (0)