


























在 Jenkins CI 环境中构建 React 项目时,遇到了以下错误:
Error: btoa is not defined
11 | };
12 | const QkImagePreview = (props: QkImagePreviewType) => {
> 13 | const { i18n, t } = useLingui();
| ^^^^^^^^^^^
14 | const [visible, setVisible] = useState(false);
这个错误发生在使用 @lingui/macro 进行国际化构建时。有趣的是,这个错误只在 Jenkins 环境中出现,在本地 Windows 环境中构建是正常的。
创建 src/utils/btoa-polyfill.ts:
// btoa polyfill for Node.js
if (typeof btoa === 'undefined') {
global.btoa = function (str: string) {
return Buffer.from(str, 'binary').toString('base64');
};
}
export {};
修改 vite.config.ts:
import { defineConfig, loadEnv } from 'vite';
// ... 其他导入
import './src/utils/btoa-polyfill';
export default defineConfig(({ mode }) => {
// ... 配置内容
});
1. 这个 polyfill 只在构建时需要,不会影响到生产环境的代码
2. 该解决方案适用于所有使用 Lingui + Vite 的项目在 Node.js 环境下的构建
3. 如果使用其他构建工具(如 webpack),可能需要调整 polyfill 的引入方式
{
"@lingui/core": "^5.1.0",
"@lingui/macro": "^5.1.0",
"@lingui/react": "^5.1.0",
"vite": "^4.3.9"
}
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。