From 67de3195ca757147c8f13dd6e0c631fcf127aa49 Mon Sep 17 00:00:00 2001 From: tomastrajan Date: Tue, 31 Oct 2023 14:12:21 +0100 Subject: [PATCH] feat(esm): use .mjs ext in import / export statements of compiled files BREAKING CHANGE: add .mjs extenstion in import / export statements - support for esbuild --- src/lib/compiler/typescript-compiler.ts | 30 ++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/src/lib/compiler/typescript-compiler.ts b/src/lib/compiler/typescript-compiler.ts index c2fd282..2478779 100644 --- a/src/lib/compiler/typescript-compiler.ts +++ b/src/lib/compiler/typescript-compiler.ts @@ -1,4 +1,4 @@ -import { lstatSync, readdirSync, renameSync } from 'fs'; +import { lstatSync, readdirSync, readFileSync, renameSync, writeFileSync } from 'fs'; import * as ts from 'typescript'; export const compileToEsNext = (filePaths: string[], outputDir: string): void => { @@ -7,12 +7,36 @@ export const compileToEsNext = (filePaths: string[], outputDir: string): void => declaration: true, outDir: outputDir, moduleResolution: ts.ModuleResolutionKind.NodeJs, - target: ts.ScriptTarget.ES5, + target: ts.ScriptTarget.ES2020, module: ts.ModuleKind.ESNext }; ts.createProgram(filePaths, compilerOptionsNext).emit(); renameJsFilesToMJs(outputDir); + addMJsExtensionToImportStatements(outputDir); +}; + +export const addMJsExtensionToImportStatements = (outputDir: string): void => { + const children = readdirSync(outputDir); + + if (children.length === 0) { + return; + } + + children.forEach(file => { + const path = `${outputDir}/${file}`; + if (lstatSync(path).isDirectory()) { + addMJsExtensionToImportStatements(path); + } else { + if (path.endsWith('.mjs')) { + const content = readFileSync(path, 'utf8'); + if (content) { + const contentWithExtensions = content.replace(/';/g, ".mjs';"); + writeFileSync(path, contentWithExtensions, 'utf8'); + } + } + } + }); }; export const renameJsFilesToMJs = (outputDir: string) => { @@ -39,7 +63,7 @@ export const compileToUMD = (filePaths: string[], outputDir: string): void => { declaration: true, outDir: outputDir, moduleResolution: ts.ModuleResolutionKind.NodeJs, - target: ts.ScriptTarget.ES2016, + target: ts.ScriptTarget.ES2020, module: ts.ModuleKind.UMD }; ts.createProgram(filePaths, compilerOptionsUMD).emit();