First problem :
Trying HMR
example given in webpack documentation in this link : https://webpack.js.org/guides/hot-module-replacement/. As mentioned in title : "Gotchas", i tried removing child which was added when app
loads for the first time, then i tried calling component()
function again to append in new element returned triggered by changed print.js
module.
In browser i get this when i change text in print.js
, which seems to work but when i press the button i keep getting old text value in print.js
Browser console screen shot on change in print.js
:
Screen shot when i click click me and check the console button (its not the text i have updated, its old text) :
My entry file main.js
:
import _ from 'lodash';
import printMe from './print.js';
function component() {
var element = document.createElement('div');
var btn = document.createElement('button');
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
btn.innerHTML = 'Click me and check the console!';
btn.onclick = printMe;
element.appendChild(btn);
return element;
}
let element = component(); // Store the element to re-render on print.js changes
document.body.appendChild(element);
if (module.hot) {
module.hot.accept('./print.js', function() {
console.log('Accepting the updated printMe module!');
document.body.removeChild(element);
element = component(); // Re-render the "component" to update the click handler
document.body.appendChild(element);
});
}
My Print.js
file :
export default function printMe() {
console.log('Updating123 and print.js...');
}
Second Problem :
I simplified previous problem to return simple text from print.js
and console logged text inside module.hot and found even weird behaviors:
component()
function triggered from module.hot.accept
callback function logs same old text on first time change inside print.js
(simple text4 is text before changes done in print.js
)
[WDS] App updated. Recompiling...
client?81da:223 [WDS] App hot update...
log.js:24 [HMR] Checking for updates on the server...
main.jsx:14 Accepting the updated printMe module!
main.jsx:15 <div>simple text4</div>
log.js:24 [HMR] Updated modules:
log.js:24 [HMR] - ./src/print.js
log.js:24 [HMR] App is up to date.
& changing second time inside print.js
does not log anything in browser console :
[WDS] App updated. Recompiling...
client?81da:223 [WDS] App hot update...
log.js:24 [HMR] Checking for updates on the server...
log.js:24 [HMR] Updated modules:
log.js:24 [HMR] - ./src/print.js
log.js:24 [HMR] App is up to date.
main.js
code :
import printMe from './print.js';
function component() {
var element = document.createElement('div');
element.innerHTML = printMe();
return element;
}
document.body.appendChild(component());
if (module.hot) {
module.hot.accept('./print.js', function() {
console.log('Accepting the updated printMe module!');
console.log(component());
});
}
print.js
code :
export default function printMe() {
var a = 'simple text2';
return a;
}