1+ // Adapted from,
2+ // typescript-esm-example
3+ // By Andrey Sakharov
4+ // Original: https://github.com/muturgan/typescript-esm-example/blob/main/buildtools/fix-imports.js
5+ // MIT License: https://github.com/muturgan/typescript-esm-example/blob/main/LICENSE
6+
7+ import { extname , join } from 'path' ;
8+ import { existsSync , readdirSync , readFileSync , statSync , writeFileSync } from 'fs' ;
9+
10+ const START_PATH = join ( process . cwd ( ) , 'dist/esm' ) ;
11+ const IMPORT_REGEXP = / ^ ( ( i m p o r t | e x p o r t ) [ ^ ' ; ] * f r o m " ( \. \/ | ( \. \. \/ ) + ) [ ^ " ; ] * ) " / g;
12+ const JUST_ADD_AN_EXTENSION = `$1.js"` ;
13+ const ADD_INDEX_FILE = `$1/index.js"` ;
14+ const JS_EXT = '.js' ;
15+
16+ /**
17+ * @param {string } rootPath
18+ */
19+ function fixImportsAtFolder ( rootPath ) {
20+ const entries = readdirSync ( rootPath ) ;
21+
22+ entries . forEach ( ( entry ) => {
23+ const entryPath = join ( rootPath , entry ) ;
24+ if ( entry . endsWith ( JS_EXT ) ) {
25+ fixImportsAtFile ( entryPath ) ;
26+ }
27+ else {
28+ const extName = extname ( entry ) ;
29+ if ( ! extName ) {
30+ const stat = statSync ( entryPath ) ;
31+ if ( stat . isDirectory ( ) ) {
32+ fixImportsAtFolder ( entryPath ) ;
33+ }
34+ }
35+ }
36+ } ) ;
37+ }
38+
39+ /**
40+ *
41+ * @param {string } filePath
42+ */
43+ function fixImportsAtFile ( filePath ) {
44+ const content = readFileSync ( filePath ) . toString ( 'utf8' ) ;
45+ const lines = content . split ( '\n' ) ;
46+ const fixedLines = lines . map ( ( l ) => {
47+ if ( ! l . match ( IMPORT_REGEXP ) ) {
48+ return l ;
49+ }
50+
51+ const [ _ , importPath ] = l . split ( `"` ) ;
52+ const fullPath = join ( filePath , '..' , importPath ) ;
53+ const exists = existsSync ( fullPath ) ;
54+ if ( exists === false ) {
55+ return l . replace ( IMPORT_REGEXP , JUST_ADD_AN_EXTENSION ) ;
56+ }
57+
58+ const stat = statSync ( fullPath ) ;
59+ const isDirectory = stat . isDirectory ( ) ;
60+ if ( isDirectory === true ) {
61+ return l . replace ( IMPORT_REGEXP , ADD_INDEX_FILE ) ;
62+ }
63+
64+ return l ;
65+ } ) ;
66+ const withFixedImports = fixedLines . join ( '\n' ) ;
67+ writeFileSync ( filePath , withFixedImports ) ;
68+ }
69+
70+ fixImportsAtFolder ( START_PATH ) ;
0 commit comments