forked from onedayitwillmake/CirclePackingJS
-
Notifications
You must be signed in to change notification settings - Fork 13
/
create-js-bundles.mjs
205 lines (159 loc) · 5.8 KB
/
create-js-bundles.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
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
import { readFile, writeFile, access, unlink } from 'fs/promises';
import { F_OK } from 'fs';
import { join as joinPath, resolve as resolvePath, dirname } from 'path';
import { fileURLToPath } from 'url';
import { rollup } from 'rollup';
import { program } from 'commander';
import terser from '@rollup/plugin-terser';
import cleanup from 'rollup-plugin-cleanup';
import replace from '@rollup/plugin-replace';
program
.option('-u, --umd', 'create umd export')
.option('-n, --nodemjs', 'generate node module (mjs)')
.option('-c, --commonjs', 'generate commonjs module')
.option('-m, --minify', 'minify output')
.parse(process.argv);
const __dirname = dirname(fileURLToPath(import.meta.url));
const basePath = __dirname;
const options = program.opts();
const buildData = await prepareBuildData({
scripts: ['circlepacker.js'],
srcPath: joinPath(basePath, 'src'),
distPath: joinPath(basePath, 'dist'),
minify: !!options.minify,
umd: !!options.umd,
nodemjs: !!options.nodemjs,
commonjs: !!options.commonjs,
date: new Date(),
jsModuleName: 'circlepacker',
});
program.version(buildData.pkg.version);
await Promise.all(
buildData.scripts.map(async scriptFileName => {
const scriptFilePath = joinPath(buildData.srcPath, scriptFileName);
const jsFileContent = await bundleJsFile(scriptFilePath, buildData);
const fileSuffixes = [];
let extension = 'js';
if (!buildData.umd && !buildData.nodemjs && !buildData.commonjs) {
fileSuffixes.push('esm');
}
if (buildData.minify) {
fileSuffixes.push('min');
}
if (buildData.nodemjs) {
fileSuffixes.push('node');
extension = 'mjs';
}
if (buildData.commonjs) {
fileSuffixes.push('cjs');
}
const fileParts = [buildData.jsModuleName, ...fileSuffixes, extension];
const distFileName = fileParts.join('.').toLowerCase();
const distFilePath = joinPath(buildData.distPath, distFileName);
try {
await access(distFilePath, F_OK);
await unlink(distFilePath);
} catch (e) {}
return writeFile(distFilePath, jsFileContent);
})
);
async function bundleJsFile(filePath, buildData, isWorker) {
const rollupPlugins = [];
const replacements = {};
replacements[
`const workerPath = params.workerPath ? params.workerPath : './CirclePackWorker.js';`
] = '';
if (buildData.nodemjs || buildData.commonjs) {
replacements['this.useWorker = params.useWorker === false ? false : true'] = '';
replacements[`if (this.useWorker) {`] = 'if (false) {';
replacements[` extends CirclePackerBrowser`] = '';
replacements[`super(params);`] = '';
replacements[`if (!this.isAnimationLoopActive) {`] = 'if (true) {';
replacements[`super.handleWorkerResponse(response);`] = '';
replacements[`super.updateListeners(response);`] = '';
replacements[`super.forceMovement();`] = '';
replacements[`super.startLoop();`] = '';
replacements[`super.destroy();`] = '';
}
if (buildData.umd) {
replacements[`export class CirclePacker `] = 'export default class CirclePacker ';
replacements[`export function pack`] = 'function pack ';
}
rollupPlugins.push(
replace({ preventAssignment: false, values: replacements, delimiters: ['', ''] })
);
if (buildData.minify) {
rollupPlugins.push(terser());
}
if (isWorker) {
rollupPlugins.push(cleanup());
}
const rollupOptions = {
input: filePath,
plugins: rollupPlugins,
};
const rollupBundle = await rollup(rollupOptions);
let generationOptions = {
format: 'module',
name: buildData.jsModuleName,
};
if (buildData.umd || buildData.commonjs) {
generationOptions = {
format: 'umd',
name: buildData.jsModuleName,
};
}
const bundleResult = await rollupBundle.generate(generationOptions);
let jsFileContent = bundleResult.output[0].code;
if (!isWorker && jsFileContent.includes('new Worker')) {
jsFileContent = await handleWorkers(jsFileContent, buildData);
}
if (!isWorker && !buildData.minify) {
let typeCommentsFile = await loadFile(joinPath(buildData.srcPath, 'types.js'));
let typeComments = typeCommentsFile.fileContent.replace(/^.*\[workerPath\].*$\n/gm, '');
if (buildData.nodemjs || buildData.commonjs) {
typeComments = typeComments.replace(/^.*\[animationLoop=true\].*$\n/gm, '');
typeComments = typeComments.replace(/^.*\[useWorker=true\].*$\n/gm, '');
typeComments = typeComments.replace(/^.*\[onMoveStart\].*$\n/gm, '');
typeComments = typeComments.replace(/^.*\[onMoveEnd\].*$\n/gm, '');
}
jsFileContent = `${typeComments}
${jsFileContent}`;
}
if (!isWorker) {
const year = buildData.date.getFullYear();
const banner = `/*! ${buildData.pkg.name} v${buildData.pkg.version} | ${buildData.pkg.license} (c) ${year} ${buildData.pkg.author} | ${buildData.pkg.homepage} */`;
jsFileContent = `${banner}
${jsFileContent}`;
}
return jsFileContent;
}
async function handleWorkers(fileContent, buildData) {
const workerInstantiation =
/new Worker\([a-zA-Z]+\s*,\s*{\s*type\s*:\s*['"]\s*module\s*['"]\s*}\s*\)/gm;
const workerFilePath = resolvePath(buildData.srcPath, 'CirclePackWorker.js');
const workerCode = await bundleJsFile(workerFilePath, buildData, true);
const workerFileContent = fileToBlobURL(workerCode);
fileContent = fileContent.replace(workerInstantiation, `new Worker(${workerFileContent})`);
return fileContent;
}
async function prepareBuildData(data = {}) {
const pkg = await loadJSONFile(joinPath(basePath, 'package.json'));
const buildData = {
pkg,
...data,
};
return buildData;
}
async function loadFile(filePath) {
const fileContent = await readFile(filePath, { encoding: 'utf8' });
return { filePath, fileContent };
}
async function loadJSONFile(filePath) {
const { fileContent } = await loadFile(filePath);
return JSON.parse(fileContent);
}
function fileToBlobURL(fileContent, type = 'text/javascript') {
const fileContentStr = JSON.stringify(fileContent);
return 'URL.createObjectURL(new Blob([' + fileContentStr + "],{type:'" + type + "'}))";
}