-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild.js
100 lines (72 loc) · 2.37 KB
/
build.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import { dirname } from 'node:path';
import { rollup } from 'rollup';
import { createProgram } from 'typescript';
import rollupGzip from 'rollup-plugin-gzip';
import rollupTerser from '@rollup/plugin-terser';
import { fileURLToPath } from 'node:url';
import { readFile } from 'node:fs/promises';
const FOLDER_NAME_SRC = 'src';
const FOLDER_NAME_DIST = 'dist';
const FILE_NAME_MODULE = 'scroll-padlock';
const pathRoot = dirname(fileURLToPath(import.meta.url));
const fileContentJsDocTypes = await readFile(`${pathRoot}/${FOLDER_NAME_SRC}/types.js`, 'utf8');
const jsDocTypedefs = fileContentJsDocTypes.match(/\/\*\*[\s\S]*?@typedef[\s\S]*?\*\//g)?.reduce((acc, typedef) => {
const match = typedef.match(/@typedef\s+(\w+)/);
if (match) {
acc[match[1]] = typedef;
}
return acc;
}, {});
const rollupResult = await rollup({
input: `${pathRoot}/${FOLDER_NAME_SRC}/index.js`,
plugins: [
{
transform: (code) => ({
code: code.replace(
/\/\*\*\s*@typedef\s*\{import\(['"].*['"]\)\.(\w+)\}\s*\1\s*\*\//g,
(match, typeName) => jsDocTypedefs?.[typeName] || match,
),
map: null,
}),
},
],
});
const moduleNameCamelCase = FILE_NAME_MODULE.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
await Promise.all([
'es',
'umd',
].reduce((tasks, format) => {
for (let versionIndex = 0; versionIndex < 2; versionIndex += 1) {
const plugins = [];
let suffixes = '';
if (format !== 'es') {
suffixes += `.${format}`;
}
if (versionIndex % 2) {
plugins.push(rollupTerser());
suffixes += '.min';
}
plugins.push(rollupGzip());
tasks.push(rollupResult.write({
sourcemap: true,
format,
name: moduleNameCamelCase,
file: `${pathRoot}/${FOLDER_NAME_DIST}/${FILE_NAME_MODULE}${suffixes}.js`,
plugins,
}));
}
return tasks;
}, []));
const pathDtsFile = `${pathRoot}/${FOLDER_NAME_DIST}/${FILE_NAME_MODULE}.d.ts`;
createProgram([
`${pathRoot}/${FOLDER_NAME_DIST}/${FILE_NAME_MODULE}.js`,
], {
allowJs: true, // include JS files
declaration: true, // generate .d.ts files
emitDeclarationOnly: true, // only output declarations
declarationMap: true, // create declaration maps
outFile: pathDtsFile, // output single .d.ts file
paths: {
[FILE_NAME_MODULE]: [`${pathRoot}/${FOLDER_NAME_DIST}/${FILE_NAME_MODULE}.js`],
},
}).emit();