chore: HMRRuntime injection (wip)

This commit is contained in:
Igor Randjelovic
2021-03-24 17:27:35 +01:00
parent 3a28f9eef6
commit 8855ca4373
13 changed files with 384 additions and 41 deletions

View File

@@ -0,0 +1,96 @@
// @ts-nocheck
// This is a runtime module - included by nativescript-hot-loader
// todo: log correct message format for CLI to pick up
// todo: build CLI service to listen for state changes
// ---
import { Http } from '@nativescript/core'
let __NS_DEV_HOST_URL__;
Promise.race(__NS_DEV_HOST_IPS__
.map(ip => `http://${ip}:8238/`)
.map(async url => {
await Http.request({
method: 'get',
url
})
return url;
})).then(winner => {
__NS_DEV_HOST_URL__ = winner
})
if(module.hot) {
module.hot.dispose(() => {
console.log('Disposing entry file?!')
// require('@nativescript/core').Application.resetRootView()
})
const orig = global.__onLiveSync
const log = (type, info) => {
console.log(`[nds] HMR ${type}:`, info)
// console.log(__NS_DEV_HOST_IPS__[0])
if(__NS_DEV_HOST_URL__) {
Http.request({
method: 'post',
url: __NS_DEV_HOST_URL__,
content: JSON.stringify({
type,
info
})
}).catch(err => {
console.log(err)
})
}
}
log('init')
module.hot.addStatusHandler(status => {
log('status', status)
})
global.__onLiveSync = async function () {
// handle hot updated on LiveSync
console.log('~~~ livesynced ~~~')
log('checking')
await module.hot.check().catch(err => {
log('checking-failed', err)
});
log('checked')
log('applying')
await module.hot.apply({
ignoreUnaccepted: false,
ignoreDeclined: false,
ignoreErrored: false,
onDeclined(info) {
log('declined', info)
},
onUnaccepted(info) {
log('unaccepted', info)
},
onAccepted(info) {
log('accepted', info)
},
onDisposed(info) {
log('disposed', info)
},
onErrored(info) {
log('errored', info)
}
}).catch((err) => {
log('applying-failed', err)
})
// log('applying')
// await module.hot.apply()
log('applying-done')
// await module.hot.apply()
setTimeout(() => {
orig();
});
};
// global.__onLiveSync()
}

View File

@@ -1,5 +1,6 @@
import { relative } from "path";
import { relative, resolve } from "path";
import dedent from "ts-dedent";
import fs from 'fs';
// note: this will bail even if module.hot appears in a comment
const MODULE_HOT_RE = /module\.hot/
@@ -11,6 +12,16 @@ export default function loader(content: string, map: any) {
}
const opts = this.getOptions();
// used to inject the HMR runtime into the entry file
if(opts.injectHMRRuntime) {
const hmrRuntimePath = resolve(__dirname, './hmr.runtime.js')
const hmrRuntime = fs.readFileSync(hmrRuntimePath).toString()
.split('// ---')[1]
.replace('//# sourceMappingURL=hmr.runtime.js.map', '')
return this.callback(null, `${content}\n${hmrRuntime}`, map)
}
const relativePath = relative(
opts.appPath ?? this.rootContext,
this.resourcePath