-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathsvelte-kit-import-hook.mjs
74 lines (70 loc) · 1.87 KB
/
svelte-kit-import-hook.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
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
/* !! This project can't be ESM yet, so hack it to get sveltekit to work. !! */
import babelCore from "@babel/core"
import * as t from "@babel/types"
/** transform code */
function transform(code, filename) {
if (
filename.includes("/@sveltejs/kit/") &&
code.includes("svelte.config.js")
) {
let transformed = false
const newCode = babelCore.transformSync(code, {
babelrc: false,
plugins: [
{
visitor: {
StringLiteral(path) {
if (path.node.value === "svelte.config.js") {
// The configuration file loads `svelte.config.mjs`.
path.replaceWith(t.stringLiteral("svelte.config.mjs"))
transformed = true
}
},
},
},
],
})
if (!transformed) {
return code
}
return `${newCode.code}`
}
return code
}
/**
* @param {string} url
* @param {{
* format: string,
* }} context If resolve settled with a `format`, that value is included here.
* @param {Function} defaultLoad
* @returns {Promise<{
* format: !string,
* source: !(string | ArrayBuffer | SharedArrayBuffer | Uint8Array),
* }>}
*/
export async function load(url, context, defaultLoad) {
const result = await defaultLoad(url, context, defaultLoad)
return {
format: result.format,
source: transform(`${result.source}`, url),
}
}
/**
* @param {!(string | SharedArrayBuffer | Uint8Array)} source
* @param {{
* format: string,
* url: string,
* }} context
* @param {Function} defaultTransformSource
* @returns {Promise<{ source: !(string | SharedArrayBuffer | Uint8Array) }>}
*/
export async function transformSource(source, context, defaultTransformSource) {
const result = await defaultTransformSource(
source,
context,
defaultTransformSource,
)
return {
source: transform(`${result.source}`, context.url),
}
}