D
D
Denis2018-02-27 13:23:07
JavaScript
Denis, 2018-02-27 13:23:07

Hot Module Replacement live reload for native JavaScript not working?

I have a single module, it is also an entry point (entry) - index.js. I'm trying to implement Live Reload in it so far using a simple example. And so far nothing has worked. In theory, to make a Live Reload, you need to replace the link to the old module with a new link, all this is done in the module.hot.accept callback, which I do. Please help me figure out what my mistake is. The bottom line is that by changing the value of the variable greeting , the changes are pulled up without reloading the page. Here is a link to the project on Github:
https://github.com/denis862008/test

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-02-27
@den0820

Option 1 . Hot swapping of the module itself:

const greetings = 'Hello, friend';
let h1;

function say() {
  h1 = document.createElement('h1');
  h1.innerHTML = greetings;
  document.body.appendChild(h1);
}

say();

if (module.hot) {
  module.hot.dispose(() => {
    document.body.removeChild(h1);
  });

  module.hot.accept();
}

Option 2 . Child Module Hot Swap:
Add the greetings.js module :
const greetings = 'Hello, friend';

export default greetings;

and change the main module like this:
import './styles.css';

let greetings = require('./greetings').default;
let h1;

function say() {
  h1 = document.createElement('h1');
  h1.innerHTML = greetings;
  document.body.appendChild(h1);
}

say();

if (module.hot) {
  module.hot.accept('./greetings', () => {
    greetings = require('./greetings').default;
    document.body.removeChild(h1);
    say();
  });
}

If transpiling modules from ES6 to CommonJS is not used , then this should also work:
import './styles.css';
import greetings from './greetings';

let h1;

function say() {
  h1 = document.createElement('h1');
  h1.innerHTML = greetings;
  document.body.appendChild(h1);
}

say();

if (module.hot) {
  module.hot.accept('./greetings', () => {
    document.body.removeChild(h1);
    say();
  });
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question