Skip to content

Commit ddeb493

Browse files
Royston-Shufflebotham-i2pvasek
authored andcommitted
Fix filename to js identifier conversion
The previous fix didn't preserve numbers in the middle/end of the name. - added new unit tests - fixed up code to pass new tests - fixed 'ts-ignore' lines
1 parent b83c843 commit ddeb493

File tree

2 files changed

+20
-8
lines changed

2 files changed

+20
-8
lines changed

src/__tests__/parser.ts

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -898,20 +898,30 @@ describe('parser', () => {
898898

899899
describe('getDefaultExportForFile', () => {
900900
it('should filter out forbidden symbols', () => {
901-
// @ts-ignore
902-
const result = getDefaultExportForFile({ fileName: 'a-b' })
901+
const result = getDefaultExportForFile({
902+
fileName: 'a-b'
903+
} as ts.SourceFile);
903904
assert.equal(result, 'ab');
904905
});
905906

906907
it('should remove leading non-letters', () => {
907-
// @ts-ignore
908-
const result = getDefaultExportForFile({ fileName: '---123aba' })
908+
const result = getDefaultExportForFile({
909+
fileName: '---123aba'
910+
} as ts.SourceFile);
909911
assert.equal(result, 'aba');
910912
});
911913

914+
it('should preserve numbers in the middle', () => {
915+
const result = getDefaultExportForFile({
916+
fileName: '1Body2Text3'
917+
} as ts.SourceFile);
918+
assert.equal(result, 'Body2Text3');
919+
});
920+
912921
it('should not return empty string', () => {
913-
// @ts-ignore
914-
const result = getDefaultExportForFile({ fileName: '---123' })
922+
const result = getDefaultExportForFile({
923+
fileName: '---123'
924+
} as ts.SourceFile);
915925
assert.equal(result.length > 0, true);
916926
});
917927
});

src/parser.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -846,9 +846,11 @@ export function getDefaultExportForFile(source: ts.SourceFile) {
846846

847847
// JS identifiers must starts with a letter, and contain letters and/or numbers
848848
// So, you could not take filename as is
849-
const identifier = filename.replace(/[^A-Za-z]*|[^0-9.]*/g, '')
849+
const identifier = filename
850+
.replace(/^[^A-Z]*/gi, '')
851+
.replace(/[^A-Z0-9]*/gi, '');
850852

851-
return identifier.length ? identifier : 'DefaultName'
853+
return identifier.length ? identifier : 'DefaultName';
852854
}
853855

854856
function getParentType(prop: ts.Symbol): ParentType | undefined {

0 commit comments

Comments
 (0)