nollup: if (module) { } can cause a potential error.

can cause Error: โ€˜moduleโ€™ is not defined

https://github.com/PepsRyuu/nollup/blob/master/docs/hmr.md

if (import.meta.module) {
    module.hot.accept(() => {
        window.location.reload();
    });
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import.meta

sorry for my poor English.

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 17 (7 by maintainers)

Most upvoted comments

Weโ€™ve all been there! Even experienced engineers I teach make the same mistake occasionally. Iโ€™ve have worked with many senior engineers over the years who struggle to configure Webpack. Wanting to understand how bundlers worked was one of the reasons I started this project. ๐Ÿ™‚ If you ever get the chance, I highly recommend challenging yourself to write your own very basic bundler. Itโ€™s one of my favourite exercises I like to give to any student of mine. ๐Ÿ˜

I see. Thank you very much for your help.

Even when I usually write differenct codes, I have a hard time separating the context(node/compiled) of JavaScript as needed.

I hope this will be a lesson for me. haha ๐Ÿ˜„

From the looks of it, you just need to use something to remove the module code. Usually the module.hot logic is handled by a third-party plugin that automatically inserts it and removes it in production. You have a few options here.

  • Use @rollup/plugin-terser to remove the code.
terser({
    compress: {
        dead_code: true,
        global_defs: {
            module: false
        }
    }
});

You can see this in the documentation here: https://github.com/PepsRyuu/nollup/blob/master/docs/hmr.md#additional-build-configuration-for-hmr

  • Alternatively you can create your own plugin to inject the code:
process.env.BUILD !== 'production' && {
    transform(code, id) {
        if (id.includes('index.js')) {
            return code + `
                if (module) {
                    module.hot.accept(() => {
                        window.location.reload();
                    })
                }
           `;
        }
    }
},

Personally I would choose the second option, as it prevents your code from containing bundler specific logic. ๐Ÿ˜ƒ

Ah the error is in the compiled code. Gotcha. Having a look into it!