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

问题描述 投票:0回答:1

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

reactjs next.js react-bootstrap primereact react-server-components
1个回答
3
投票

我发现这实际上很容易做到。您只需要定义一个 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"),
    },
  },
};
© www.soinside.com 2019 - 2024. All rights reserved.