Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/build/vite/rollup-url-to-module-plugin/index.mjs
4772 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
/**
7
* @type {() => import('rollup').Plugin}
8
*/
9
export function urlToEsmPlugin() {
10
return {
11
name: 'import-meta-url',
12
async transform(code, id) {
13
if (this.environment?.mode === 'dev') {
14
return;
15
}
16
17
// Look for `new URL(..., import.meta.url)` patterns.
18
const regex = /new\s+URL\s*\(\s*(['"`])(.*?)\1\s*,\s*import\.meta\.url\s*\)?/g;
19
20
let match;
21
let modified = false;
22
let result = code;
23
let offset = 0;
24
25
while ((match = regex.exec(code)) !== null) {
26
let path = match[2];
27
28
if (!path.startsWith('.') && !path.startsWith('/')) {
29
path = `./${path}`;
30
}
31
const resolved = await this.resolve(path, id);
32
33
if (!resolved) {
34
continue;
35
}
36
37
// Add the file as an entry point
38
const refId = this.emitFile({
39
type: 'chunk',
40
id: resolved.id,
41
});
42
43
const start = match.index;
44
const end = start + match[0].length;
45
46
const replacement = `import.meta.ROLLUP_FILE_URL_OBJ_${refId}`;
47
48
result = result.slice(0, start + offset) + replacement + result.slice(end + offset);
49
offset += replacement.length - (end - start);
50
modified = true;
51
}
52
53
if (!modified) {
54
return null;
55
}
56
57
return {
58
code: result,
59
map: null
60
};
61
}
62
};
63
}
64
65