import webpack from "webpack";

import type { Configuration } from "webpack";

const { ProvidePlugin } = webpack;

/**
 * In some cases it is more than recommend to use a lightweight alternative
 * to React in your frontend. E. g. for plugin developers creating frontend
 * solutions to non-logged-in users to reduce load time.
 *
 * Note: You need to apply `skipExternals: ["react", "react-dom"]`, too!
 */
function applyPreact(config: Configuration, disableChunks = false) {
    // Disable splitChunks so no `vendor~banner.js` is created
    if (disableChunks) {
        delete config.optimization.splitChunks;
    }

    // Implement preact and JSX transform through and webpack
    // https://preactjs.com/guide/v10/getting-started#aliasing-in-webpack
    config.resolve.alias = {
        ...(config.resolve.alias || {}),
        react: "preact/compat",
        "react-dom": "preact/compat",
    };

    // https://github.com/preactjs/preact-compat/issues/161#issuecomment-590806041
    config.plugins.push(
        new ProvidePlugin({
            h: ["preact", "h"],
        }),
    );
}

export { applyPreact };
