-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
fix-ext.mjs
47 lines (41 loc) · 1.44 KB
/
fix-ext.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import path from 'node:path';
import fs from 'node:fs/promises';
import { globby } from 'globby';
// Because we're using .mts files, TS compiles to .mjs files disregarding the target. So here we
// manually rename the common.js files and their imports to .js
const mjsFiles = await globby(['dist/cjs/**/*.mjs', '!**/node_modules']);
mjsFiles.forEach(async (pathname) => {
// 1. Rename imports
const fileContent = await fs.readFile(pathname, 'utf8');
await fs.writeFile(
pathname,
fileContent.replaceAll(/require\(["']([^"']*)\.mjs["']\)/g, "require('$1.js')"),
);
// 2. Rename files
const newPath = path.format({
...path.parse(pathname),
base: '',
ext: '.js',
});
console.log(`Renaming ${pathname} to ${newPath}...`);
await fs.rename(pathname, newPath);
});
// Similarly, we rename the .d.mts files to .d.ts. This is because Typescript `node16` target will
// masquerade as ESM otherwise.
const dmtsFiles = await globby(['dist/cjs/**/*.d.mts', '!**/node_modules']);
dmtsFiles.forEach(async (pathname) => {
// 1. Rename imports from `.mjs` to `.js`
const fileContent = await fs.readFile(pathname, 'utf8');
await fs.writeFile(
pathname,
fileContent.replaceAll(/from '([^']*)\.mjs'/g, "from '$1.js'"),
);
// 2. Rename files
const newPath = path.format({
...path.parse(pathname),
base: '',
ext: '.ts',
});
console.log(`Renaming ${pathname} to ${newPath}...`);
await fs.rename(pathname, newPath);
});