问题错误
window/document is not defined
这个错误出以下情况中:
- 调用了window或者document对象的非React组件函数中,
- 引入了一些第三方组件,里面全局调用了window或者document对象
解决方案:
使用官方的<BrowserOnly />
组件进行包裹,以iconfont文件为例:
import React from "react";
import BrowserOnly from "@docusaurus/BrowserOnly";
import classnames from "classnames";
import "./iconfont.css";
interface IconfontProps {
iconName: string;
className?: string;
iconPrefix?: string;
[restProps: string]: any;
}
declare global {
interface Window {
CPS_ICONFONT_INIT: boolean;
}
}
// 这段代码这里通过判断window上是否存在CPS_ICONFONT_INIT变量来确保某个script不被重复添加
export function IconfontInit(src: string = "") {
return (
<BrowserOnly>
{() => {
if (window.CPS_ICONFONT_INIT) return;
const ICONFIGT_SRC = src || "//at.alicdn.com/t/c/font_3959151_f86s1etjfv.js";
const scriptElem = document.createElement("script");
scriptElem.src = ICONFIGT_SRC;
document.body.appendChild(scriptElem);
window.CPS_ICONFONT_INIT = true;
return <div className="hidden">{window.CPS_ICONFONT_INIT}</div>;
}}
</BrowserOnly>
);
}
export default function Iconfont({ iconName, className = "", iconPrefix = "", ...restProps }: IconfontProps) {
IconfontInit();
return (
<svg className={classnames("iconfontDefault", className)} aria-hidden="true" {...restProps}>
<use xlinkHref={`#${iconPrefix}${iconName}`} />
</svg>
);
}
安装@docusaurus/plugin-ideal-image插件以来sharp错误
1、出现“ sharp: Installation error: tunneling socket could not be established, cause=connect ECONNREFUSED 127.0.0.1:1081”问题
解决方法:删除代理
pnpm config delete https-proxy pnpm config delete proxy
2、出现:"sharp: Installation error: certificate has expired"
解决方法:设置镜像与sharp的依赖libvips
pnpm config set sharp_binary_host "https://npmmirror.com/mirrors/sharp" pnpm config set sharp_libvips_binary_host "https://npmmirror.com/mirrors/sharp-libvips"
pnpm install sharp
无法正确的提示类型,类似import Image from "@theme/IdealImage";
中,theme/IdealImage
不能正确的识别
// tsconfig.json
{
"compilerOptions": {
// 添加 docusaurus 的类型文件夹到这里
"typeRoots": ["node_modules/@docusaurus"],
}
}
svgo在单页多个svg的页面中,id变成#a、#b错误
触发原因
- 只要是通过
import xxxx from 'xxx.svg'
方式引用的svg都会发生
单个页面当存在多个svg图片时,svgo会对svg的内联id名称进行压缩,所有id都会变成#a、#b,但svg文件的id空间是基于全局的,所以除了第一个svg能正确显示,其他svg图片都会发生id错误,它们都只只会使用第一个svg的id
因为svgo内置在docusaurusV3中,同时也是嵌套在webcpak里面,通过@svgr/webpack
来调用,学前端的都知道webpack是什么玩意,难用,配置不统一,配置难,所以造成了想在docusaurusV3解决变成了不可能,不同的webpack版本,不同的svgo版本
解决方案
- svgo中配置
cleanupIds
:cleanupIds
和cleanupIDs
,并配置为minify: false
- svgo中配置自定义前缀`
- svgo嵌套进了webpack中,v3版本只能通过自定义插件来重新配置webpack配置
- V2版本可以直接在config中配置webpack
deep Webpack merge magic
配置过的都懂,webpack配置恶心,过渡耦合,版本版本不清晰,不一致,不生效,反正基本无法解决
相关Issue
- Multiple inline SVGs on a page can clash · Issue #8297 · facebook/docusaurus
- fix(svgo): enable prefixIds by default by ilteoood · Pull Request #8191 · facebook/docusaurus
解决方法
- 使用img的src单独引入svg图片
- 将svg完全写入tsx中