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
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"),
},
},
};
-
2A 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$/
– nicholasCommented Aug 10, 2023 at 19:37
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"],
},
],
],
},
};
-
1any affiliation? /help/promotion please show how to use the tool.– starballCommented Mar 1 at 22:26
-
1While 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 Commented Mar 4 at 15:26