-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathbuild.mjs
More file actions
executable file
·205 lines (192 loc) · 5.16 KB
/
build.mjs
File metadata and controls
executable file
·205 lines (192 loc) · 5.16 KB
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
#!/usr/bin/env node
import { join, resolve } from 'path';
import {
readFileSync,
rmSync,
readdirSync,
statSync,
existsSync,
copyFileSync,
cpSync,
writeFileSync,
} from 'fs';
import { execFileSync } from 'child_process';
const TO_TRANSFORM_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx'];
const STATIC_FILES = [
{
src: 'LICENSE',
dest: 'LICENSE',
},
{
src: 'README.md',
dest: 'README.md',
},
{
src: 'CHANGELOG.md',
dest: 'CHANGELOG.md',
},
];
async function babelBuild(sourceDir, buildDir) {
const cwd = process.cwd();
// get config file
const configFile = join(cwd, '.babelrc.mjs');
try {
const result = execFileSync(
'babel',
[
sourceDir,
'--out-dir',
buildDir,
'--config-file',
configFile,
'--extensions',
TO_TRANSFORM_EXTENSIONS.join(','),
],
{
env: {
...process.env,
NODE_ENV: 'production',
},
encoding: 'utf8',
shell: true,
}
);
console.log(result);
} catch (error) {
console.error(error);
throw new Error(error);
}
}
async function createTypes() {
try {
const tscResult = execFileSync('tsc', ['--project', 'tsconfig.prod.json'], {
env: {
...process.env,
NODE_ENV: 'production',
},
encoding: 'utf8',
shell: true,
});
console.log(tscResult);
const tscAliasResult = execFileSync('tsc-alias', ['-p', 'tsconfig.prod.json'], {
env: {
...process.env,
NODE_ENV: 'production',
},
encoding: 'utf8',
shell: true,
});
console.log(tscAliasResult);
} catch (error) {
console.error(error);
throw new Error(error);
}
}
function copyFiles(sourceDir, buildDir) {
for (const target of STATIC_FILES) {
const sourcePath = resolve(sourceDir, target.src);
const destPath = resolve(buildDir, target.dest);
// check if it exists
if (!existsSync(sourcePath)) {
continue;
}
// check if dir or files
const stats = statSync(sourcePath);
if (stats.isFile()) {
copyFileSync(sourcePath, destPath);
} else if (stats.isDirectory()) {
cpSync(sourcePath, destPath, { recursive: true });
}
}
}
function writePackageJson(buildDir) {
// first read the package.json
const cwd = process.cwd();
const pkgJsonPath = join(cwd, 'package.json');
const packageJson = JSON.parse(readFileSync(pkgJsonPath, { encoding: 'utf8' }));
// delete data that mustn't be in the published package.json
delete packageJson.scripts;
delete packageJson.devDependencies;
delete packageJson.bin;
// add property for treeshaking
packageJson.sideEffects = false;
// add additional properties
// type module is to tell that code is in esm
// types is to tell what is the main typing file
// main is to tell what is the main file
packageJson.type = 'module';
packageJson.types = './index.d.ts';
packageJson.main = './index.js';
// add exports
packageJson.exports = {
'./package.json': './package.json',
'.': {
default: {
types: './index.d.ts',
default: './index.js',
},
},
'./*': {
default: {
types: './*/index.d.ts',
default: './*/index.js',
},
},
};
writeFileSync(join(buildDir, 'package.json'), JSON.stringify(packageJson, null, 2), 'utf-8');
}
function getAllFiles(dirPath, arrayOfFiles = []) {
const files = readdirSync(dirPath);
files.forEach((file) => {
const fullPath = join(dirPath, file);
if (statSync(fullPath).isDirectory()) {
getAllFiles(fullPath, arrayOfFiles);
} else {
arrayOfFiles.push(fullPath);
}
});
return arrayOfFiles;
}
function formatBytes(bytes, decimals = 2) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
async function build() {
const cwd = process.cwd();
// get the build directory and remove it if it exists
const buildDir = join(cwd, 'dist');
rmSync(buildDir, { recursive: true, force: true });
// build
const sourceDir = join(cwd, 'src');
babelBuild(sourceDir, buildDir);
// create types
createTypes();
// copy static files
copyFiles(cwd, buildDir);
// create package.json for the builded library
writePackageJson(buildDir);
// log files with extensions
// 1. get all files in build directory
const allFiles = getAllFiles(buildDir);
// 2. calc files sizes
const fileSizes = allFiles.map((file) => {
const stats = statSync(file);
return { path: file, size: stats.size };
});
// 3. order from the lighter to the heavier
fileSizes.sort((a, b) => a.size - b.size);
// 4. calc total size
const totalSize = fileSizes.reduce((acc, file) => acc + file.size, 0);
// 5. log results
fileSizes.forEach((file) => {
console.log(`${formatBytes(file.size).padEnd(10)} | ${file.path}`);
});
console.log('---------------------------------');
console.log(`Total dimension: ${formatBytes(totalSize)}`);
console.log('---------------------------------');
}
build();