/
parse5-plugin.ts
98 lines (89 loc) · 2.39 KB
/
parse5-plugin.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
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
import fs from 'fs-extra';
import { aliasPlugin } from './alias-plugin';
import { join } from 'path';
import type { BuildOptions } from '../../utils/options';
import rollupCommonjs from '@rollup/plugin-commonjs';
import rollupResolve from '@rollup/plugin-node-resolve';
import { rollup, OutputChunk, Plugin } from 'rollup';
import { minify } from 'terser';
export function parse5Plugin(opts: BuildOptions): Plugin {
return {
name: 'parse5Plugin',
resolveId(id) {
if (id === 'parse5') {
return id;
}
return null;
},
async load(id) {
if (id === 'parse5') {
return await bundleParse5(opts);
}
return null;
},
generateBundle(_, bundle) {
Object.keys(bundle).forEach(fileName => {
// not minifying, but we are reducing whitespace
const chunk = bundle[fileName] as OutputChunk;
if (chunk.type === 'chunk') {
chunk.code = chunk.code.replace(/ /g, ' ');
}
});
},
};
}
async function bundleParse5(opts: BuildOptions) {
const fileName = `parse5-${opts.parse5Verion.replace(/\./g, '_')}-bundle-cache${opts.isProd ? '.min' : ''}.js`;
const cacheFile = join(opts.scriptsBuildDir, fileName);
try {
return await fs.readFile(cacheFile, 'utf8');
} catch (e) {}
const rollupBuild = await rollup({
input: '@parse5-entry',
plugins: [
{
name: 'parse5EntryPlugin',
resolveId(id) {
if (id === '@parse5-entry') {
return id;
}
return null;
},
load(id) {
if (id === '@parse5-entry') {
return `export { parse, parseFragment } from 'parse5';`;
}
return null;
},
},
aliasPlugin(opts),
rollupResolve(),
rollupCommonjs(),
],
});
const { output } = await rollupBuild.generate({
format: 'iife',
name: 'PARSE5',
footer: ['export const parse = PARSE5.parse;', 'export const parseFragment = PARSE5.parseFragment;'].join('\n'),
preferConst: true,
strict: false,
});
let code = output[0].code;
if (opts.isProd) {
const minified = await minify(code, {
ecma: 2018,
module: true,
compress: {
ecma: 2018,
passes: 2,
},
format: {
ecma: 2018,
comments: false,
},
});
code = minified.code;
}
await fs.writeFile(cacheFile, code);
return code;
}