-
Notifications
You must be signed in to change notification settings - Fork 254
/
require_vendor.mjs
30 lines (26 loc) · 1006 Bytes
/
require_vendor.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
import MagicString from 'magic-string';
const REQUIRE_POLYFILLS =
`const { TextEncoder, TextDecoder } = require('../vendor/text-encoding');
const { encode: btoa, decode: atob } = require('../vendor/base64');\n`
export class RequireVendor {
/**
* Take the compiled source code input; types are expected to already have been removed.
* Add the TextEncoder, TextDecoder, atob, btoa requires.
*
* @param {string} code - source code of the module being transformed
* @param {string} id - module id (usually the source file name)
* @returns {{ code: string; map: import('magic-string').SourceMap }}
*/
transform(code, id) {
if (!id.includes('web_byte_utils')) {
return;
}
// MagicString lets us edit the source code and still generate an accurate source map
const magicString = new MagicString(code);
magicString.prepend(REQUIRE_POLYFILLS);
return {
code: magicString.toString(),
map: magicString.generateMap({ hires: true })
};
}
}