如何在非Next.js的React库中实现兼容Next.js的通用Link组件
如何在非Next.js的React UI库中实现自动适配next/link的Link组件
项目背景
- 项目A:基于React开发的无头UI库,未使用Next.js框架,作为通用组件库供其他项目导入使用
- 项目B:基于React+Next.js的前端核心项目,需要导入项目A的组件
需求
在项目A中开发一个Link组件,当该组件被导入到项目B时,表现完全等同于next/link,同时必须兼容客户端渲染(CSR)与服务端渲染(SSR)场景。
已尝试的方案及问题
方案1:使用require动态加载next/link
const Link = (props: LinkProps) => { try { return createElement( // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore require.resolve("next/link").default, props, props.children ); } catch (e) { console.log("error getting nextLinkPath or create element", e); return createElement("a", props, props.children); } }; export default Link;
出现的问题:
- 在项目B的客户端组件中运行时,抛出
ReferenceError: require is not defined - 在项目B的服务端组件中,
require.resolve("next/link").default返回undefined
方案2:使用async/await动态import
const Link = (props: LinkProps) => { loadNextComponent(props).then((component) => { return component; }); }; const loadNextComponent = async (props: LinkProps) => { try { // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore const NextLink = (await (import(/* @vite-ignore */ "next/link") as any) .default) as string; return createElement(NextLink, { ...props }, props.children); } catch (error) { console.error("Error loading next component:", error); return <a {...props}>{props.children}</a>; } };
出现的问题:
- 项目A运行时,Vite抛出错误:
[vite] Internal server error: Failed to resolve import "next/link" from "src/components/atoms/Link/Link.tsx". Does the file exist? - 项目B中,React抛出警告:
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined.,原因是异步函数无法直接在组件中返回JSX节点
核心疑问
如何在未依赖Next.js的React UI库中,实现一个Link组件,使其在导入到Next.js项目时自动适配为next/link,同时兼容CSR和SSR两种渲染场景?
内容的提问来源于stack exchange,提问作者Frankey
相关产品推荐
相关产品推荐

