/
build.ts
60 lines (46 loc) · 1.47 KB
/
build.ts
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
48
49
50
51
52
53
54
55
56
57
58
59
60
import path from 'node:path'
import fs from 'fs-extra'
import { fileURLToPath } from 'node:url'
import { execa } from 'execa'
const root = path.basename(fileURLToPath(import.meta.url))
const bin = (name: string) => path.resolve(root, '../node_modules/.bin/' + name)
async function main() {
await execa(
bin('unbuild'),
[],
{ stdio: 'inherit' }
)
await patchCommomJs()
await patchESModule()
}
async function patchCommomJs() {
const indexPath = path.resolve(root, '../dist/index.cjs')
let indexCodes = await fs.readFile(indexPath, 'utf-8')
const moduleExportsLine = `module.exports = __toCommonJS(src_exports);`
if (indexCodes.includes(moduleExportsLine)) {
const name = 'dtsPlugin'
indexCodes = indexCodes.replace(
moduleExportsLine,
`module.exports = ${name};\n${name}['default'] = ${name};`
)
await fs.writeFile(indexPath, indexCodes)
}
}
const cjsBridge = `
import __cjs_url__ from 'url';
import __cjs_path__ from 'path';
import __cjs_mod__ from 'module';
const __filename = __cjs_url__.fileURLToPath(import.meta.url);
const __dirname = __cjs_path__.dirname(__filename);
const require = __cjs_mod__.createRequire(import.meta.url);
`
async function patchESModule() {
const indexPath = path.resolve(root, '../dist/index.mjs')
let indexCodes = await fs.readFile(indexPath, 'utf-8')
indexCodes = cjsBridge + indexCodes
await fs.writeFile(indexPath, indexCodes)
}
main().catch(error => {
console.error(error)
process.exit(1)
})