4

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?

2 Answers 2

5

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
  • 2
    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
    Commented Aug 10, 2023 at 19:37
0

You can try this swc plugin if you are using next.js. https://github.com/coder-xiaotian/swc-useclient

install yarn add -D use-client

then config next.js

const nextConfig = {
  experimental: {
    swcPlugins: [
      [
        "use-client",
        {
          include: ["@mui/material", "@mui/icons-material","antd", "@ant-design/icons"],
        },
      ],
    ],
  },
};
2
  • 1
    any affiliation? /help/promotion please show how to use the tool.
    – starball
    Commented Mar 1 at 22:26
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review
    – pigrammer
    Commented Mar 4 at 15:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.