Override a module's exports with a webpack plugin

Viewed 338

I'd like to override a module's export before webpack requires it and builds it.

In the examples below, how would you override the exported getType?

The module.exports.getType = () => "page"; is of course wrong, but that's theoretically what I'd like to do.

Here's the example page:

const BasicPage = () => "Hello Basic page";

const getType = () => "unknown";
export { getType };

export default BasicPage;

In the webpack config, here's the plugin part

config.plugins.push({
    apply: (compiler) => {
        compiler.hooks.compilation.tap("ModuleExportsHijack", (compilation) => {
            compilation.hooks.buildModule.tap("SourceMapDevToolModuleOptionsPlugin", (module) => {
                if ((module.request || "").includes("/pages/basic.js")) {
                    // HOW TO OVERRIDE AN EXPORTS?
                    // module.exports.getType = () => "page";
                    console.log("module --", module);
                }
            });
        });
    },
});
0 Answers
Related