diff --git a/packages/js/src/plugins/rollup/type-definitions.spec.ts b/packages/js/src/plugins/rollup/type-definitions.spec.ts new file mode 100644 index 00000000000000..0fcb6889b68d9b --- /dev/null +++ b/packages/js/src/plugins/rollup/type-definitions.spec.ts @@ -0,0 +1,62 @@ +import { typeDefinitions } from './type-definitions'; +describe('typeDefinitions', () => { + it('should emit correct .d.ts filenames for various file formats', () => { + const mockBundle = { + 'index.js': { + type: 'chunk', + isEntry: true, + fileName: 'index.js', + facadeModuleId: '/project/src/index.ts', + exports: ['default', 'namedExport1', 'namedExport2'], + }, + 'index1.js': { + type: 'chunk', + isEntry: true, + fileName: 'index.cjs', + facadeModuleId: '/project/src/index.ts', + exports: ['default', 'namedExport1', 'namedExport2'], + }, + 'index2.js': { + type: 'chunk', + isEntry: true, + fileName: 'index.mjs', + facadeModuleId: '/project/src/index.ts', + exports: ['default', 'namedExport1', 'namedExport2'], + }, + 'index3.js': { + type: 'chunk', + isEntry: true, + fileName: 'index.cjs.js', + facadeModuleId: '/project/src/index.ts', + exports: ['default', 'namedExport1', 'namedExport2'], + }, + 'index4.js': { + type: 'chunk', + isEntry: true, + fileName: 'index.mjs.js', + facadeModuleId: '/project/src/index.ts', + exports: ['default', 'namedExport1', 'namedExport2'], + }, + }; + + const mockOpts = {}; // Can be left empty for this scenario + + const mockEmitFile = jest.fn(); + + const plugin = typeDefinitions({ projectRoot: '/project' }); + + // Simulate the `this` context of a Rollup plugin + const mockContext = { + emitFile: mockEmitFile, + }; + + // Run the plugin's `generateBundle` function + (async function testPlugin() { + await plugin.generateBundle.call(mockContext, mockOpts, mockBundle); + + mockEmitFile.mock.calls.forEach(([{ fileName }]) => { + expect(fileName).toBe('index.d.ts'); + }); + })(); + }); +}); diff --git a/packages/js/src/plugins/rollup/type-definitions.ts b/packages/js/src/plugins/rollup/type-definitions.ts index f82ddf505bab5d..33cf9811c72242 100644 --- a/packages/js/src/plugins/rollup/type-definitions.ts +++ b/packages/js/src/plugins/rollup/type-definitions.ts @@ -38,7 +38,13 @@ export function typeDefinitions(options: { projectRoot: string }) { /\.[cm]?[jt]sx?$/, '' ); - const dtsFileName = file.fileName.replace(/\.[cm]?js$/, '.d.ts'); + + // Replace various JavaScript file extensions (e.g., .js, .cjs, .mjs, .cjs.js, .mjs.js) with .d.ts for generating type definition file names. + const dtsFileName = file.fileName.replace( + /(\.cjs|\.mjs|\.js|\.cjs\.js|\.mjs\.js)$/, + '.d.ts' + ); + const relativeSourceDtsName = JSON.stringify('./' + entrySourceDtsName); const dtsFileSource = hasDefaultExport ? stripIndents`