-
Notifications
You must be signed in to change notification settings - Fork 3
/
plugin.js
106 lines (94 loc) · 2.61 KB
/
plugin.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import { createUnplugin } from 'unplugin'
import { EXAMPLE_COMPONENT_PREFIX, EXAMPLE_MODULE_PREFIX } from './remark.js'
import path from 'path'
import MagicString from 'magic-string'
import { unescape } from './util.js'
// finds the value of the src prop on <Example /> so we can parse the contents into a virtual file
const RE_SRC = new RegExp(
`src: (\\/\\* ${EXAMPLE_COMPONENT_PREFIX}(\\d) \\*\\/ )String.raw\`([\\s\\S*]*?)(?<!\\\\)\``,
'gm'
)
export default createUnplugin(
(
/**
* @type {{ extensions?: string[]}}
*/
options = {}
) => {
const { extensions = ['.svelte.md', '.md', '.svx'] } = options
const examples = {}
let viteServer
return {
name: 'mdsvexample-plugin',
transformInclude(id) {
return extensions.some((ext) => id.endsWith(ext)) || id.includes(EXAMPLE_MODULE_PREFIX)
},
resolveId(id) {
if (id.includes(EXAMPLE_MODULE_PREFIX)) {
return id
}
},
load(id) {
if (id.includes(EXAMPLE_MODULE_PREFIX)) {
if (examples[id]) {
const code = examples[id]
return code
}
throw new Error(`Example src not found for ${id}`)
}
},
transform(code, id) {
if (extensions.some((ext) => id.endsWith(ext))) {
const matches = code.matchAll(RE_SRC)
const s = new MagicString(code)
for (const [, comment, i, src] of matches) {
// change path of module so that it's sibling to the mdsvex file
const base = path.relative(process.cwd(), id)
const importPath = `${base}/${EXAMPLE_MODULE_PREFIX}${i}.svelte`
// store example code
examples[importPath] = unescape(src)
// update mdsvex component
s
// update import path
.replace(
new RegExp(
`import ${EXAMPLE_COMPONENT_PREFIX}${i} from "${EXAMPLE_MODULE_PREFIX}${i}.svelte"`,
'g'
),
`import ${EXAMPLE_COMPONENT_PREFIX}${i} from "${importPath}"`
)
// remove comment used to mark where code is
.replace(comment, '')
}
return {
code: s.toString(),
/** @type {any} */
map: s.generateMap()
}
}
if (id.includes(EXAMPLE_MODULE_PREFIX)) {
return {
code,
map: {
mappings: null
}
}
}
},
vite: {
configureServer(server) {
viteServer = server
},
handleHotUpdate() {
// reload page when example is updated - would be nice to trigger HMR on owner svelte component instead
Object.keys(examples).forEach((key) => {
viteServer.moduleGraph.invalidateModule(viteServer.moduleGraph.getModuleById(key))
viteServer.ws.send({
type: 'full-reload'
})
})
}
}
}
}
)