UNPKG

2.18 kBJavaScriptView Raw
1const { compareSignatures, isComponent } = require('@prefresh/utils');
2
3module.exports = function preactRefreshPlugin(config, pluginOptions) {
4 return {
5 knownEntrypoints: ['@prefresh/core'],
6 async transform({ contents, urlPath, isDev }) {
7 if (!isDev || !urlPath.endsWith('.js')) return;
8
9 return {
10 result: `
11 require('@prefresh/snowpack/runtime');
12 import * as $OriginalModule$ from ${JSON.stringify(urlPath)};
13 let $CurrentModule$ = $OriginalModule$;
14
15 const compareSignaturesForPrefreshment = ${compareSignatures.toString()};
16 const shouldPrefreshBind = ${isComponent.toString()}
17
18 const __module_exports__ = []
19
20 const prevRefreshReg = window.$RefreshReg$ || (() => {});
21 const prevRefreshSig = window.$RefreshSig$ || (() => {});
22
23 window.$RefreshSig$ = () => {
24 let status = 'begin';
25 let savedType;
26 return (type, key, forceReset, getCustomHooks) => {
27 if (!savedType) savedType = type;
28 status = window.__PREFRESH__.sign(type || savedType, key, forceReset, getCustomHooks, status);
29 };
30 };
31
32 window.$RefreshReg$ = (type, id) => {
33 __module_exports__.push(type.name);
34 };
35
36 ${contents}
37
38 window.$RefreshSig$ = prevRefreshSig;
39 window.$RefreshReg$ = prevRefreshReg;
40
41 if (import.meta.hot && __module_exports__.some(shouldPrefreshBind)) {
42 import.meta.hot.accept(({ module }) => {
43 try {
44 for (let i in module) {
45 if (typeof module[i] === 'function') {
46 if (i in $CurrentModule$) {
47 // We could add a check here on i.name if it's a component.
48 compareSignaturesForPrefreshment(
49 $CurrentModule$[i],
50 module[i]
51 );
52 }
53 }
54 }
55 $CurrentModule$ = module;
56 } catch(e) {
57 import.meta.hot.invalidate();
58 }
59 });
60 }
61 `
62 };
63 }
64 };
65}