UNPKG

2.25 kBPlain TextView Raw
1import { Configuration } from 'webpack';
2
3export function isLocal(path: string) {
4 if (path) {
5 if (path.startsWith(':')) {
6 return false;
7 } else if (path.startsWith('http:')) {
8 return false;
9 } else if (path.startsWith('https:')) {
10 return false;
11 } else if (path.startsWith('data:')) {
12 return false;
13 }
14
15 return true;
16 }
17
18 return false;
19}
20
21export function extractParts(content: CheerioStatic) {
22 const sheets = content('link[href]')
23 .filter((_, e) => isLocal(e.attribs.href))
24 .remove()
25 .toArray();
26 const scripts = content('script[src]')
27 .filter((_, e) => isLocal(e.attribs.src))
28 .remove()
29 .toArray();
30 const files: Array<string> = [];
31
32 for (const sheet of sheets) {
33 files.push(sheet.attribs.href);
34 }
35
36 for (const script of scripts) {
37 files.push(script.attribs.src);
38 }
39
40 return files;
41}
42
43export function getTemplates(entry: Configuration['entry']) {
44 const templates: Array<string> = [];
45
46 if (typeof entry === 'string') {
47 if (entry.endsWith('.html')) {
48 templates.push(entry);
49 }
50 } else if (Array.isArray(entry)) {
51 templates.push(...entry.filter(e => e.endsWith('.html')));
52 } else if (typeof entry !== 'function') {
53 Object.keys(entry).forEach(key => {
54 const value = entry[key];
55 templates.push(...getTemplates(value));
56 });
57 }
58
59 return templates;
60}
61
62export function replaceEntries(existingEntries: Array<string>, oldEntry: string, newEntries: Array<string>) {
63 for (let i = 0; i < existingEntries.length; i++) {
64 if (existingEntries[i] === oldEntry) {
65 existingEntries.splice(i, 1, ...newEntries);
66 break;
67 }
68 }
69}
70
71export function setEntries(config: Configuration, template: string, entries: Array<string>) {
72 if (typeof config.entry === 'string') {
73 config.entry = entries;
74 } else if (Array.isArray(config.entry)) {
75 replaceEntries(config.entry, template, entries);
76 } else if (typeof config.entry !== 'function') {
77 Object.keys(config.entry).forEach(key => {
78 const value = config.entry[key];
79
80 if (value === template) {
81 config.entry[key] = entries;
82 } else if (Array.isArray(value)) {
83 replaceEntries(value, template, entries);
84 }
85 });
86 }
87}