Skip to content

Commit 9e7e054

Browse files
authored
Merge pull request #232 from tomastrajan/master
feat(esm): use .mjs ext in import / export statements of compiled files
2 parents 28cb50b + 67de319 commit 9e7e054

File tree

1 file changed

+27
-3
lines changed

1 file changed

+27
-3
lines changed

src/lib/compiler/typescript-compiler.ts

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { lstatSync, readdirSync, renameSync } from 'fs';
1+
import { lstatSync, readdirSync, readFileSync, renameSync, writeFileSync } from 'fs';
22
import * as ts from 'typescript';
33

44
export const compileToEsNext = (filePaths: string[], outputDir: string): void => {
@@ -7,12 +7,36 @@ export const compileToEsNext = (filePaths: string[], outputDir: string): void =>
77
declaration: true,
88
outDir: outputDir,
99
moduleResolution: ts.ModuleResolutionKind.NodeJs,
10-
target: ts.ScriptTarget.ES5,
10+
target: ts.ScriptTarget.ES2020,
1111
module: ts.ModuleKind.ESNext
1212
};
1313

1414
ts.createProgram(filePaths, compilerOptionsNext).emit();
1515
renameJsFilesToMJs(outputDir);
16+
addMJsExtensionToImportStatements(outputDir);
17+
};
18+
19+
export const addMJsExtensionToImportStatements = (outputDir: string): void => {
20+
const children = readdirSync(outputDir);
21+
22+
if (children.length === 0) {
23+
return;
24+
}
25+
26+
children.forEach(file => {
27+
const path = `${outputDir}/${file}`;
28+
if (lstatSync(path).isDirectory()) {
29+
addMJsExtensionToImportStatements(path);
30+
} else {
31+
if (path.endsWith('.mjs')) {
32+
const content = readFileSync(path, 'utf8');
33+
if (content) {
34+
const contentWithExtensions = content.replace(/';/g, ".mjs';");
35+
writeFileSync(path, contentWithExtensions, 'utf8');
36+
}
37+
}
38+
}
39+
});
1640
};
1741

1842
export const renameJsFilesToMJs = (outputDir: string) => {
@@ -39,7 +63,7 @@ export const compileToUMD = (filePaths: string[], outputDir: string): void => {
3963
declaration: true,
4064
outDir: outputDir,
4165
moduleResolution: ts.ModuleResolutionKind.NodeJs,
42-
target: ts.ScriptTarget.ES2016,
66+
target: ts.ScriptTarget.ES2020,
4367
module: ts.ModuleKind.UMD
4468
};
4569
ts.createProgram(filePaths, compilerOptionsUMD).emit();

0 commit comments

Comments
 (0)