-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathindex.js
62 lines (53 loc) · 1.68 KB
/
index.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
import { compile } from '@riotjs/compiler'
import { Transformer } from '@parcel/plugin'
import sourceMap from '@parcel/source-map'
import { basename } from 'path'
const SourceMap = sourceMap.default
const CONFIG_FILES = ['.riotrc', '.riotrc.js', 'riot.config.js']
const PACKAGE_KEY = 'riot'
/**
* Generate the hmr code depending on the tag generated by the compiler
* @param {string} path - path to the component file
* @returns {string} the code needed to handle the riot hot reload
*/
function hotReload(path) {
return `;(() => {
if (module.hot) {
const hotReload = require('@riotjs/hot-reload').default
module.hot.accept()
if (module.hot.data) {
const component = require('./${path}').default;
hotReload(component)
}
}
})()`
}
export default new Transformer({
async loadConfig({ config }) {
const riotConfig =
(await config.getConfig(CONFIG_FILES, {
packageKey: PACKAGE_KEY,
})) || {}
const shouldInvalidateOnStartup =
(riotConfig?.filePath?.endsWith('.js')) ||
riotConfig?.filePath?.endsWith(CONFIG_FILES[0])
if (shouldInvalidateOnStartup) {
config.invalidateOnStartup()
}
return riotConfig.contents || {}
},
async transform({ asset, config = {}, options }) {
const source = await asset.getCode()
const sourceMap = new SourceMap(options.projectRoot)
const { code, map } = compile(source, {
file: asset.filePath,
...config,
})
// the suffix will be added only for the HMR
const suffix = config.hot ? hotReload(basename(asset.filePath)) : ''
asset.type = 'js'
asset.setCode(`${code}${suffix}`)
asset.setMap(sourceMap.addVLQMap(map))
return [asset]
},
})