Skip to content

Commit

Permalink
Merge pull request #232 from tomastrajan/master
Browse files Browse the repository at this point in the history
feat(esm): use .mjs ext in import / export statements of compiled files
  • Loading branch information
nivekcode authored Oct 31, 2023
2 parents 28cb50b + 67de319 commit 9e7e054
Showing 1 changed file with 27 additions and 3 deletions.
30 changes: 27 additions & 3 deletions src/lib/compiler/typescript-compiler.ts
Original file line number Diff line number Diff line change
@@ -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 => {
Expand All @@ -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) => {
Expand All @@ -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();
Expand Down

0 comments on commit 9e7e054

Please sign in to comment.