reactjsnext.jsreact-bootstrapprimereactreact-server-components

Server components: Can we use webpack to add "use client" in modules from compponent library?


React server components make us use the "use client" directive on top of files. This basically breaks react components library (like ReactBootstrap and PrimeReact) and makes us create wrapper files just to add "use client" in each module exported by this lib. But is there some Webpack feature that we can use to add this "use client" for us in that kind of library?


Solution

  • I figured out that it is actually pretty easy to do this. You just need to define a Webpack loader to do that:

    // loaders/use-client-loader.js
    
    module.exports = function (source) {
      return `"use client";\n` + source;
    };
    
    
    //Now declare the loader in webpack
    
    /// if you are using with nextJS:
    /// next.config.js
    
    /** @type {import('next').NextConfig} */
    const nextConfig = {
      webpack: function (config, options) {
        config.module.rules.push({
          test: [/node_modules[\\/]primereact[\\/.].*\.js$/], /// replace here make match your package
          loader: require.resolve("./loaders/use-client-loader.js"),
        });
        return config;
      },
    };
    
    module.exports = nextConfig;
    
    // if you are not using nextJS (find how to edit your webpack config):
    module.exports = {
      // ...some config here
      module: {
        rules: {
          test: [/node_modules[\\/]primereact[\\/.].*\.js$/], /// replace here make match your package
          loader: require.resolve("./loaders/use-client-loader.js"),
        },
      },
    };