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

在NX Monorepo中使用react-i18next与MUI组件时实例未定义

解决NX Monorepo中react-i18next useTranslation返回undefined的问题

1. 将react-i18next设为组件包的peer依赖

组件包如果把react-i18next、i18next、react作为常规依赖打包,会导致宿主项目和组件包各自加载一份独立的依赖实例,useTranslation钩子无法找到宿主项目中初始化的i18n实例。

修改组件包的package.json,将这些依赖移到peerDependencies:

{
  "peerDependencies": {
    "react": "^18.0.0",
    "react-dom": "^18.0.0",
    "react-i18next": "^13.0.0",
    "i18next": "^23.0.0"
  }
}

同时从dependencies或devDependencies中移除这些包,避免重复打包。

2. 调整NX的模块解析配置

NX Monorepo的模块隔离机制可能导致组件包无法正确解析宿主项目的react-i18next实例。在组件包的tsconfig.json中添加路径映射,强制使用宿主项目的依赖版本:

{
  "compilerOptions": {
    "paths": {
      "react-i18next": ["../node_modules/react-i18next"],
      "i18next": ["../node_modules/i18next"],
      "react": ["../node_modules/react"]
    }
  }
}

路径根据你的monorepo目录结构调整,确保指向根目录的node_modules。

3. 配置组件包的打包工具排除外部依赖

如果使用rollup或webpack打包组件包,需要将react-i18next等依赖标记为外部依赖,不打包进组件代码:

Rollup示例(rollup.config.js)

export default {
  // ...其他配置
  external: ['react', 'react-dom', 'react-i18next', 'i18next']
};

Webpack示例(webpack.config.js)

module.exports = {
  // ...其他配置
  externals: {
    react: 'react',
    'react-dom': 'react-dom',
    'react-i18next': 'react-i18next',
    i18next: 'i18next'
  }
};

4. 验证宿主项目的i18n初始化

确保宿主项目的根组件通过I18nextProvider正确包裹,且i18n实例初始化完成:

import { I18nextProvider } from 'react-i18next';
import i18n from './i18n'; // 你的i18n初始化文件

function App() {
  return (
    <I18nextProvider i18n={i18n}>
      {/* 应用内容 */}
    </I18nextProvider>
  );
}

export default App;

确认i18n文件中已经调用initReactI18next并完成初始化:

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

i18n
  .use(initReactI18next)
  .init({
    // 你的i18n配置
    resources: {},
    lng: 'en',
    fallbackLng: 'en',
    interpolation: {
      escapeValue: false
    }
  });

export default i18n;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 23:37:27