-
Notifications
You must be signed in to change notification settings - Fork 42
/
bundle.js
79 lines (69 loc) · 2.21 KB
/
bundle.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
import { rollup } from './rollup.browser';
import bubleJSXOnly from './bubleJSXOnly';
import svelte from './svelte';
import hypothetical from './hypothetical';
import { getLibraries } from './getLibraries';
// if HTML parser encounter </script> it stops parsing current script
// in order to avoid that, </script> should be splitted
const escapeClosingScriptTag = (code) =>
code.split('</script>').join('" + "<" + "/script>" + "');
const transformFilesToObject = (files) =>
files
.filter(
(file) => file.name.endsWith('.js') || file.name.endsWith('.svelte')
)
.reduce((accumulator, file) => {
accumulator['./' + file.name] = file.text;
return accumulator;
}, {});
export const bundle = async (files) => {
const libraries = getLibraries(files);
const outputOptions = {
format: 'iife',
name: 'bundle',
sourcemap: 'inline',
globals: libraries,
};
const inputOptions = {
input: './index.js',
plugins: [
svelte(),
hypothetical({
files: transformFilesToObject(files),
}),
bubleJSXOnly({
target: {
chrome: 71,
},
}),
],
external: Object.keys(libraries),
};
const rollupBundle = await rollup(inputOptions);
const { output } = await rollupBundle.generate(outputOptions);
// Monkey patch magic-string internals
// to support characters outside of the Latin1 range, e.g. Cyrillic.
//
// Related reading:
// - https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/btoa#Unicode_strings
// - https://github.com/Rich-Harris/magic-string/blob/3466b0230dddc95eb378ed3e0d199e36fbd1f572/src/SourceMap.js#L3
//
if (output.length !== 1) {
throw new Error(
'Expected Rollup output length to be 1. This Error is a VizHub bug if it happens.'
);
}
const { code, map } = output[0];
const escapedCode = escapeClosingScriptTag(code);
const toString = map.toString.bind(map);
map.toString = () => unescape(encodeURIComponent(toString()));
// Inspired by https://github.com/rollup/rollup/issues/121
const codeWithSourceMap =
escapedCode + '\n//# sourceMappingURL=' + map.toUrl();
return [
{
name: 'bundle.js',
text: codeWithSourceMap,
},
];
};