服务器组件:我​​们可以使用 webpack 在组件库的模块中添加“使用客户端”吗?

Vit*_*ues 4 reactjs react-bootstrap next.js primereact react-server-components

React 服务器组件让我们在文件顶部使用“use client”指令。这基本上破坏了 React 组件库(如 ReactBootstrap 和 PrimeReact),并使我们创建包装文件只是为了在该库导出的每个模块中添加“使用客户端”。但是我们是否可以使用一些 Webpack 功能在此类库中添加这个“使用客户端”?

Vit*_*ues 5

我发现这实际上很容易做到。您只需要定义一个 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"),
    },
  },
};
Run Code Online (Sandbox Code Playgroud)

  • 一个绝妙的解决方法。有两件事:1) 由于路径分隔符不同,测试正则表达式在 Windows 上不起作用,2) 如果您从 primereact 导入 css,这将破坏您的 css 文件。我通过将其调整为: `/node_modules[\\/]primereact[\\/.].*\.js$/` 来使其工作 (2认同)