diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d77596a..25d9588c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,62 @@ # eslint-plugin-import-x +## 4.6.0 + +### Minor Changes + +- [#209](https://github.com/un-ts/eslint-plugin-import-x/pull/209) [`46d2360`](https://github.com/un-ts/eslint-plugin-import-x/commit/46d2360f5ebfbd79e74a0828ac7e280973510454) Thanks [@SukkaW](https://github.com/SukkaW)! - 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. + +### Patch Changes + +- [#206](https://github.com/un-ts/eslint-plugin-import-x/pull/206) [`449738f`](https://github.com/un-ts/eslint-plugin-import-x/commit/449738f4f4b84ff24c2748cdc86185cff5840442) Thanks [@privatenumber](https://github.com/privatenumber)! - insert type prefix without new line + ## 4.5.1 ### Patch Changes diff --git a/package.json b/package.json index 6c715999..9485d468 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "eslint-plugin-import-x", - "version": "4.5.1", + "version": "4.6.0", "description": "Import with sanity.", "repository": "git+https://github.com/un-ts/eslint-plugin-import-x", "author": "JounQin (https://www.1stG.me)", @@ -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", diff --git a/src/index.ts b/src/index.ts index 5d34ef1b..bf7a43c3 100644 --- a/src/index.ts +++ b/src/index.ts @@ -72,6 +72,7 @@ import type { PluginFlatConfig, } from './types' import { importXResolverCompat } from './utils' +import { createNodeResolver } from './node-resolver' const rules = { 'no-unresolved': noUnresolved, @@ -183,4 +184,5 @@ export = { flatConfigs, rules, importXResolverCompat, + createNodeResolver } diff --git a/src/node-resolver.ts b/src/node-resolver.ts new file mode 100644 index 00000000..9b0e6b34 --- /dev/null +++ b/src/node-resolver.ts @@ -0,0 +1,68 @@ +import { ResolverFactory, CachedInputFileSystem, type ResolveOptions } from 'enhanced-resolve'; +import fs from 'node:fs'; +import type { NewResolver } from './types'; +import { isBuiltin } from 'node:module'; +import { dirname } from 'node:path'; + +interface NodeResolverOptions extends Omit { + /** + * 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 = {}): 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 }; + } + } + } +} diff --git a/src/rules/no-duplicates.ts b/src/rules/no-duplicates.ts index b4732f75..2a5d5893 100644 --- a/src/rules/no-duplicates.ts +++ b/src/rules/no-duplicates.ts @@ -172,13 +172,15 @@ function getFix( specifier.identifiers.reduce( ([text, set], cur) => { const trimmed = cur.trim() // Trim whitespace before/after to compare to our set of existing identifiers - const curWithType = - trimmed.length > 0 && preferInline && isTypeSpecifier - ? `type ${cur}` - : cur - if (existingIdentifiers.has(trimmed)) { + if (trimmed.length === 0 || existingIdentifiers.has(trimmed)) { return [text, set] } + + const curWithType = + preferInline && isTypeSpecifier + ? cur.replace(/^(\s*)/, '$1type ') + : cur + return [ text.length > 0 ? `${text},${curWithType}` : curWithType, set.add(trimmed), @@ -267,8 +269,9 @@ function getFix( ) } } else if (openBrace != null && closeBrace != null && !shouldAddDefault()) { + const tokenBefore = sourceCode.getTokenBefore(closeBrace)! // `import {...} './foo'` → `import {..., ...} from './foo'` - fixes.push(fixer.insertTextBefore(closeBrace, specifiersText)) + fixes.push(fixer.insertTextAfter(tokenBefore, specifiersText)) } // Remove imports whose specifiers have been moved into the first import. diff --git a/test/node-resolver.spec.ts b/test/node-resolver.spec.ts new file mode 100644 index 00000000..12bb7355 --- /dev/null +++ b/test/node-resolver.spec.ts @@ -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) +}) diff --git a/test/rules/no-duplicates.spec.ts b/test/rules/no-duplicates.spec.ts index f71a0d54..e9636fdc 100644 --- a/test/rules/no-duplicates.spec.ts +++ b/test/rules/no-duplicates.spec.ts @@ -70,7 +70,7 @@ ruleTester.run('no-duplicates', rule, { invalid: [ tInvalid({ code: "import { x } from './foo'; import { y } from './foo'", - output: "import { x , y } from './foo'; ", + output: "import { x, y } from './foo'; ", errors: [createDuplicatedError('./foo'), createDuplicatedError('./foo')], }), @@ -87,7 +87,7 @@ ruleTester.run('no-duplicates', rule, { // ensure resolved path results in warnings tInvalid({ code: "import { x } from './bar'; import { y } from 'bar';", - output: "import { x , y } from './bar'; ", + output: "import { x, y } from './bar'; ", settings: { 'import-x/resolve': { paths: [path.resolve('test/fixtures')], @@ -133,7 +133,7 @@ ruleTester.run('no-duplicates', rule, { tInvalid({ code: "import type { x } from './foo'; import type { y } from './foo'", - output: "import type { x , y } from './foo'; ", + output: "import type { x, y } from './foo'; ", languageOptions: { parser: require(parsers.BABEL) }, errors: [createDuplicatedError('./foo'), createDuplicatedError('./foo')], }), @@ -146,7 +146,7 @@ ruleTester.run('no-duplicates', rule, { tInvalid({ code: "import { x, /* x */ } from './foo'; import {//y\ny//y2\n} from './foo'", - output: "import { x, /* x */ //y\ny//y2\n} from './foo'; ", + output: "import { x,//y\ny//y2\n /* x */ } from './foo'; ", languageOptions: { parser: require(parsers.ESPREE) }, errors: [createDuplicatedError('./foo'), createDuplicatedError('./foo')], }), @@ -195,7 +195,7 @@ ruleTester.run('no-duplicates', rule, { tInvalid({ code: "import { } from './foo'; import {x} from './foo'", - output: "import { x} from './foo'; ", + output: "import {x } from './foo'; ", errors: [createDuplicatedError('./foo'), createDuplicatedError('./foo')], }), @@ -419,7 +419,7 @@ import {x,y} from './foo' // #2027 long import list generate empty lines tInvalid({ code: "import { Foo } from './foo';\nimport { Bar } from './foo';\nexport const value = {}", - output: "import { Foo , Bar } from './foo';\nexport const value = {}", + output: "import { Foo, Bar } from './foo';\nexport const value = {}", errors: [createDuplicatedError('./foo'), createDuplicatedError('./foo')], }), @@ -452,8 +452,8 @@ export default TestComponent; import { DEFAULT_FILTER_KEYS, BULK_DISABLED, - BULK_ACTIONS_ENABLED + } from '../constants'; import React from 'react'; @@ -493,9 +493,9 @@ export default TestComponent; ${''} import { A2, - ${''} B2, - C2} from 'bar'; + C2 + } from 'bar'; ${''} `, errors: [ @@ -822,7 +822,7 @@ describe('TypeScript', () => { code: "import type { AType as BType } from './foo'; import { CValue } from './foo'", ...parserConfig, options: [{ 'prefer-inline': true }], - output: `import { type AType as BType , CValue } from './foo'; `, + output: `import { type AType as BType, CValue } from './foo'; `, errors: [ { ...createDuplicatedError('./foo'), @@ -836,6 +836,37 @@ describe('TypeScript', () => { }, ], }), + tInvalid({ + code: ` + import { + a + } from './foo'; + import type { + b, + c, + } from './foo';`, + ...parserConfig, + options: [{ 'prefer-inline': true }], + output: ` + import { + a, + type b, + type c + } from './foo'; + `, + errors: [ + { + ...createDuplicatedError('./foo'), + line: 4, + column: 20, + }, + { + ...createDuplicatedError('./foo'), + line: 8, + column: 20, + }, + ], + }), ]), ] diff --git a/yarn.lock b/yarn.lock index dfe2a1bd..258fe862 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3413,7 +3413,7 @@ 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== @@ -3421,6 +3421,14 @@ enhanced-resolve@^5.12.0, enhanced-resolve@^5.16.0: 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"