Skip to content

Commit

Permalink
Support import-equals w/ ns.access
Browse files Browse the repository at this point in the history
  • Loading branch information
webpro committed Apr 16, 2024
1 parent 82f19f3 commit 438280e
Show file tree
Hide file tree
Showing 7 changed files with 45 additions and 0 deletions.
4 changes: 4 additions & 0 deletions packages/knip/fixtures/import-equals/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import * as NS from './my-module.js';
import local = require('./local.js');
import external = require('external');
import something = NS.something;
1 change: 1 addition & 0 deletions packages/knip/fixtures/import-equals/local.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default () => 1
1 change: 1 addition & 0 deletions packages/knip/fixtures/import-equals/my-module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const something = {};
6 changes: 6 additions & 0 deletions packages/knip/fixtures/import-equals/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"name": "@fixtures/import-equals",
"dependencies": {
"external": "*"
}
}
1 change: 1 addition & 0 deletions packages/knip/fixtures/import-equals/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
11 changes: 11 additions & 0 deletions packages/knip/src/typescript/getImportsAndExports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,17 @@ const getImportsAndExports = (
}
}

if (
isTopLevel &&
ts.isImportEqualsDeclaration(node) &&
ts.isQualifiedName(node.moduleReference) &&
ts.isIdentifier(node.moduleReference.left)
) {
// Pattern: import name = NS.identifier
const { left, right } = node.moduleReference;
if (sourceFile.locals?.get(left.text)) maybeAddAccessExpressionAsNsImport(left.text, right.text);
}

if (ts.isTypeReferenceNode(node) && ts.isQualifiedName(node.typeName)) {
const [ns, ...right] = [node.typeName.left.getText(), node.typeName.right.getText()].join('.').split('.');
const members = right.map((_r, index) => right.slice(0, index + 1).join('.'));
Expand Down
21 changes: 21 additions & 0 deletions packages/knip/test/import-equals.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { test } from 'bun:test';
import assert from 'node:assert/strict';
import { main } from '../src/index.js';
import { resolve } from '../src/util/path.js';
import baseArguments from './helpers/baseArguments.js';
import baseCounters from './helpers/baseCounters.js';

const cwd = resolve('fixtures/import-equals');

test('Find used exports through import-equal NS.member access', async () => {
const { counters } = await main({
...baseArguments,
cwd,
});

assert.deepEqual(counters, {
...baseCounters,
processed: 3,
total: 3,
});
});

0 comments on commit 438280e

Please sign in to comment.