2

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?

1 Answers1

3

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"),
    },
  },
};
  • 1
    A brilliant workaround. Two things: 1) the test regex does not work on Windows as-written because of the different path separator, and 2) this will mangle your css files if you are doing css imports from primereact. I got it to work by tweaking it to: `/node_modules[\\/]primereact[\\/.].*\.js$/` – nicholas Aug 10 '23 at 19:37