1- import * as assert from 'node:assert' ;
2- import * as util from 'node:util' ;
1+ import assert from 'node:assert' ;
2+ import util from 'node:util' ;
33
4- import * as ts from 'typescript' ;
4+ import ts from 'typescript' ;
55
66/**
77 * Adds extension to all paths imported inside MJS files
88 *
99 * Transforms:
1010 *
1111 * ```
12- * import { foo } from './bar';
13- * export { foo } from './bar';
12+ * import { foo } from './bar.js ';
13+ * export { foo } from './bar.js ';
1414 * ```
1515 *
1616 * to:
1717 *
1818 * ```
19- * import { foo } from './bar.mjs ';
20- * export { foo } from './bar.mjs ';
19+ * import { foo } from './bar.ts ';
20+ * export { foo } from './bar.ts ';
2121 * ```
2222 *
2323 */
24- export function addExtensionToImportPaths ( config : { extension : string } ) {
24+ export function changeExtensionInImportPaths ( config : { extension : string } ) {
2525 const { extension } = config ;
2626 return ( context : ts . TransformationContext ) => {
2727 const { factory } = context ;
@@ -35,13 +35,15 @@ export function addExtensionToImportPaths(config: { extension: string }) {
3535 function visitNode ( node : ts . Node ) : ts . Node {
3636 const source : string | undefined = ( node as any ) . moduleSpecifier ?. text ;
3737 if ( source ?. startsWith ( './' ) || source ?. startsWith ( '../' ) ) {
38+ const newSource = source . replace ( / \. j s $ / , extension ) ;
39+
3840 if ( ts . isImportDeclaration ( node ) ) {
3941 return factory . updateImportDeclaration (
4042 node ,
4143 node . decorators ,
4244 node . modifiers ,
4345 node . importClause ,
44- ts . createStringLiteral ( source + extension ) ,
46+ factory . createStringLiteral ( newSource ) ,
4547 node . assertClause ,
4648 ) ;
4749 }
@@ -52,7 +54,7 @@ export function addExtensionToImportPaths(config: { extension: string }) {
5254 node . modifiers ,
5355 node . isTypeOnly ,
5456 node . exportClause ,
55- ts . createStringLiteral ( source + extension ) ,
57+ factory . createStringLiteral ( newSource ) ,
5658 node . assertClause ,
5759 ) ;
5860 }
0 commit comments