Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 943
Vitor Figueredo Marques Avatar asked Oct 15 '25 19:10

Vitor Figueredo Marques


1 Answers

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"),
    },
  },
};
like image 95
Vitor Figueredo Marques Avatar answered Oct 18 '25 15:10

Vitor Figueredo Marques



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!