webpackweb-applicationswebpack-dev-serverhot-module-replacement

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"?)


Solution

  • 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 ----------------------------------
    }