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

如何用Vite与Lingui打包带.po文件的React类库

解决方案:打包React类库时包含Lingui的.po翻译文件

要在Vite构建的React类库中包含src/assets/locales下的.po翻译文件,需要同时配置Vite和Lingui的相关设置,具体如下:

1. Vite配置(vite.config.ts)

Vite默认只会打包代码文件,需要显式指定.po为资源文件,并确保库模式下资源正确输出:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  build: {
    lib: {
      entry: 'src/index.ts', // 替换为你的类库入口文件
      name: 'YourReactLib',
      formats: ['es', 'umd'],
      fileName: (format) => `your-react-lib.${format}.js`
    },
    rollupOptions: {
      // 排除React等外部依赖,避免打包进类库
      external: ['react', 'react-dom'],
      output: {
        globals: {
          react: 'React',
          reactDom: 'ReactDOM'
        }
      }
    },
    // 将.po文件纳入资源处理范围
    assetsInclude: ['**/*.po']
  }
});

配置后,Vite会将.po文件打包到dist/assets目录下,代码中引用的路径会被自动替换为正确的输出路径。

2. Lingui配置(lingui.config.ts)

确保Lingui的配置指向正确的翻译文件目录,并使用po格式:

import type { LinguiConfig } from '@lingui/conf';

const config: LinguiConfig = {
  locales: ['en', 'zh-CN'], // 替换为你的目标语言列表
  sourceLocale: 'en',
  catalogs: [
    {
      path: '<rootDir>/src/assets/locales/{locale}',
      include: ['src'],
      exclude: ['**/node_modules/**', '**/*.test.tsx', '**/*.stories.tsx']
    }
  ],
  format: 'po',
  compileNamespace: 'es' // 编译为ES模块,适配类库的模块化需求
};

export default config;

这个配置会让Lingui CLI在提取翻译时,将.po文件生成到指定目录,同时确保编译后的翻译文件符合类库的模块规范。

3. 动态加载翻译的代码规范

在你的dynamicActivate函数中,使用Vite支持的动态导入语法加载.po文件:

import { i18n } from '@lingui/core';

export async function dynamicActivate(locale: string) {
  // 注意:动态导入的路径需静态可分析,变量仅用于指定locale
  const { messages } = await import(`../assets/locales/${locale}.po`);
  i18n.load(locale, messages);
  i18n.activate(locale);
}

参考文档方向

  • Vite:重点查看Build Options中的assetsInclude配置,以及Library Mode的打包规则说明
  • Lingui:重点查看Configuration中的catalogs和format配置项,以及Dynamic Loading的类库开发指引

内容的提问来源于stack exchange,提问作者Laczkó Örs

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 03:45:06