forked from jd-opensource/micro-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
create_type.js
executable file
·65 lines (56 loc) · 1.58 KB
/
create_type.js
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
61
62
63
64
65
'use strict'
/* eslint-disable no-console */
const path = require('path')
const dts = require('dts-bundle')
const chalk = require('chalk')
const fse = require('fs-extra')
const fs = require('fs')
const cwd = process.cwd()
const pkg = require(path.join(cwd, 'package.json'))
const typingsDir = 'typings' // typings目录地址
const outPath = path.join(cwd, 'lib/index.d.ts') // 输出目录
// 判断是否是文件夹
function isDirectory (dir) {
try {
const stat = fs.statSync(dir)
return stat.isDirectory()
} catch (e) {
return false
}
}
// 添加Reference依赖
function addReference (target) {
try {
if (fs.statSync(target).isFile() && path.extname(target) === '.ts') {
const preSource = fs.readFileSync(outPath)
fs.writeFileSync(outPath, `/// <reference path="../${target}" />\n${preSource}`)
} else if (isDirectory(target)) {
const sources = fs.readdirSync(target) || []
for (let i = 0; i < sources.length; i++) {
addReference(path.join(target, sources[i]))
}
}
} catch (e) {
console.log(chalk.red('add references failed'), e)
}
}
function createDts () {
try {
dts.bundle({
main: path.join(cwd, 'lib', 'lib/index.d.ts'), // 入口地址
name: pkg.name, // 声明模块
removeSource: true, // 删除源文件
out: outPath, // 合并后输出地址
})
fse.removeSync(path.join(cwd, 'lib', 'lib/'))
if (isDirectory(typingsDir)) {
addReference(typingsDir)
}
} catch (e) {
console.log(
chalk.red('生成*.d.ts文件失败'),
)
throw e
}
}
createDts()