feat: latus HMR!

This commit is contained in:
cha0s 2021-03-25 05:15:39 -05:00
parent a448ac22af
commit bb7d78fdcf
3 changed files with 57 additions and 2 deletions

View File

@ -275,6 +275,45 @@ export default class Latus {
}); });
} }
refresh(plugin, M) {
const keys = Object.keys(this.hooks);
for (let j = 0; j < keys.length; j++) {
const key = keys[j];
if (this.hooks[key]) {
const index = this.hooks[key].findIndex(({plugin: hookPlugin}) => hookPlugin === plugin);
if (-1 !== index) {
this.hooks[key].splice(index, 1);
}
}
}
if (M.default) {
const {default: {hooks}} = M;
if (hooks) {
const keys = Object.keys(hooks);
debug("hooks for '%s': %O", plugin, keys);
for (let j = 0; j < keys.length; j++) {
const key = keys[j];
if (!this.hooks[key]) {
this.hooks[key] = [];
}
this.hooks[key].push({
plugin,
fn: hooks[key],
});
}
}
}
else {
debug(`'${plugin}' has no default export`);
}
const defaultConfig = this.invoke('@latus/core/config');
this.config[plugin] = {
...defaultConfig[plugin],
...this.config[plugin],
};
this.invokeFlat('@latus/core/config/alter', this.config);
}
static runtimePath(path) { static runtimePath(path) {
try { try {
R.resolve(path); R.resolve(path);

View File

@ -41,6 +41,7 @@ module.exports = async (latus) => {
const contexts = new Set(); const contexts = new Set();
paths.forEach((path) => { paths.forEach((path) => {
source.push(` module.hot.accept('${path}', () => {`); source.push(` module.hot.accept('${path}', () => {`);
source.push(` window.latus.refresh('${path}', require('${path}'));`);
source.push(` window.latus.invoke('@latus/core/hmr', '${path}');`); source.push(` window.latus.invoke('@latus/core/hmr', '${path}');`);
source.push(' });'); source.push(' });');
const context = join(dirname(R.resolve(path)), 'assets'); const context = join(dirname(R.resolve(path)), 'assets');

View File

@ -1,6 +1,21 @@
import {useContext} from 'react'; import {useContext, useEffect, useState} from 'react';
// eslint-disable-next-line import/no-extraneous-dependencies // eslint-disable-next-line import/no-extraneous-dependencies
import {LatusContext} from '@latus/react/client'; import {LatusContext} from '@latus/react/client';
export default () => useContext(LatusContext); export default () => {
const [, setId] = useState(0);
const latus = useContext(LatusContext);
useEffect(() => {
if (!latus.hooks['@latus/core/hmr']) {
latus.hooks['@latus/core/hmr'] = [];
}
latus.hooks['@latus/core/hmr'].push({
plugin: '@latus/react/hmr',
fn: () => {
setId(Math.random());
},
});
}, [latus]);
return latus;
};