You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

主项目与自研组件库react-hook-form导入不一致致上下文失效求助

解决react-hook-form跨模块上下文失效问题

1. 强制统一依赖入口

主项目和组件库分别通过overrides(npm)或resolutions(yarn)强制使用react-hook-form的同一份入口文件,避免加载不同实例:

  • npm项目(主项目+组件库的package.json):
{
  "overrides": {
    "react-hook-form": {
      "./dist/index.cjs.js": "./dist/index.esm.mjs"
    }
  }
}
  • yarn项目(主项目+组件库的package.json):
{
  "resolutions": {
    "react-hook-form/dist/index.cjs.js": "react-hook-form/dist/index.esm.mjs"
  }
}

2. 调整组件库打包配置

确保组件库打包时不内置react-hook-form,并且输出ES模块格式:

  • Webpack配置:
module.exports = {
  externals: {
    'react-hook-form': {
      commonjs: 'react-hook-form',
      commonjs2: 'react-hook-form',
      amd: 'react-hook-form',
      module: 'react-hook-form'
    }
  },
  output: {
    libraryTarget: 'module'
  }
};
  • Rollup配置:
export default {
  external: ['react-hook-form'],
  output: {
    format: 'esm'
  }
};

3. 优化主项目模块解析

让主项目优先加载ES模块入口,确保依赖解析一致:

  • Webpack配置:
module.exports = {
  resolve: {
    extensions: ['.mjs', '.js', '.jsx'],
    mainFields: ['module', 'main']
  }
};
  • Vite配置:
export default defineConfig({
  resolve: {
    mainFields: ['module', 'main']
  }
});

4. 重置依赖环境

清理缓存后重新安装依赖,确保配置生效:

# npm
rm -rf node_modules package-lock.json && npm install

# yarn
rm -rf node_modules yarn.lock && yarn install

内容的提问来源于stack exchange,提问作者kevinls

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 17:43:12