React 服务器组件让我们在文件顶部使用“use client”指令。这基本上破坏了 React 组件库(如 ReactBootstrap 和 PrimeReact),并使我们创建包装文件只是为了在该库导出的每个模块中添加“使用客户端”。但是,我们是否可以使用一些 Webpack 功能在此类库中添加这个“使用客户端”?
我发现这实际上很容易做到。您只需要定义一个 Webpack 加载器即可做到这一点:
// 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"),
},
},
};