Skip to content

Commit

Permalink
feat: support dynamic imports
Browse files Browse the repository at this point in the history
  • Loading branch information
kazushisan committed Sep 22, 2024
1 parent 09ec27c commit 03156a0
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
22 changes: 22 additions & 0 deletions lib/util/removeUnusedExport.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -803,6 +803,28 @@ const b: B = {};`,
);
});

describe('dynamic import', () => {
it('should not remove export if its used in dynamic import', () => {
const { languageService, fileService } = setup();
fileService.set(
'/app/main.ts',
`import('./a.js');
import('./b.js');`,
);
fileService.set('/app/a.ts', `export const a = 'a';`);
fileService.set('/app/b.ts', `export default 'b';`);

removeUnusedExport({
languageService,
fileService,
targetFile: ['/app/a.ts', '/app/b.ts'],
});

assert.equal(fileService.get('/app/a.ts'), `export const a = 'a';`);
assert.equal(fileService.get('/app/b.ts'), `export default 'b';`);
});
});

describe('deleteUnusedFile', () => {
it('should not remove file if some exports are used in other files', () => {
const { languageService, fileService } = setup();
Expand Down
11 changes: 11 additions & 0 deletions lib/util/removeUnusedExport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
} from './applyCodeFix.js';
import { EditTracker } from './EditTracker.js';
import { getFileFromModuleSpecifierText } from './getFileFromModuleSpecifierText.js';
import { collectDynamicImports } from './collectDynamicImports.js';

const findFirstNodeOfKind = (root: ts.Node, kind: ts.SyntaxKind) => {
let result: ts.Node | undefined;
Expand Down Expand Up @@ -527,6 +528,8 @@ export const removeUnusedExport = ({
throw new Error('program not found');
}

const dynamicImports = collectDynamicImports({ program, fileService });

for (const file of Array.isArray(targetFile) ? targetFile : [targetFile]) {
const sourceFile = program.getSourceFile(file);

Expand All @@ -536,6 +539,13 @@ export const removeUnusedExport = ({

editTracker.start(file, sourceFile.getFullText());

const dynamicImport = dynamicImports.vertexes.get(file);

if (dynamicImport && dynamicImport.from.size > 0) {
editTracker.end(file);
continue;
}

let content = fileService.get(file);
let isUsed = false;

Expand All @@ -562,6 +572,7 @@ export const removeUnusedExport = ({
if (!isUsed && deleteUnusedFile) {
fileService.delete(file);
editTracker.delete(file);
dynamicImports.deleteVertex(file);

continue;
}
Expand Down

0 comments on commit 03156a0

Please sign in to comment.