Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

webpack-dev-server: how to preserve state with module.hot.data?

I'm using webpack-dev-server's Hot Module Replacement (HMR). In the code, I have this:

// index.js

// ...

window.enableFoo = false; // can set this to 'true' in DevTools console

if (module && module.hot) {
    module.hot.accept((err) => {
        console.error('HMR accept() error: ' + err);
    });
    module.hot.addStatusHandler(status => {
        if (status === 'apply') {
            console.log('HMR: update applied');
        }
    });
}

I'd like to preserve window.enableFoo across HMR update. However, every time the update is applied, window.enableFoo goes back to the original value set in the code, which is true here.

I read from HMR's API doc that I need to use module.hot.dispose() and module.hot.data, but I couldn't find an example on how to do this, and the doc didn't elaborate. Could someone help me?

(this post is similar, but the code is entangled with Angular and not easy to understand... also, this thread says "If you want to keep state, use dispose and module.hot.data, don't use accept"?)

like image 859
Leedehai Avatar asked Oct 19 '25 15:10

Leedehai


1 Answers

After digging, this code works. I figure I'd better paste it here in case someone is also looking for an answer.

// index.js

// ...

window.enableFoo = false; // can set this to 'true' in DevTools console

if (module && module.hot) {
    module.hot.accept((err) => {
        console.error('HMR accept() error: ' + err);
    });
    module.hot.addStatusHandler(status => {
        if (status === 'apply') {
            console.log('HMR: update applied');
        }
    });

    // added begin ----------------------------------
    module.hot.addDisposeHandler(data => {
        data.enableFoo = window.enableFoo;
    });
    if (module.hot.data) {
        window.enableFoo = module.hot.data.enableFoo;
        console.log('window.enableFoo ' + window.enableFoo);
    }
    // added end ----------------------------------
}
like image 117
Leedehai Avatar answered Oct 21 '25 20:10

Leedehai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!