Next.js集成SunEditor报错core._resourcesStateChange is not a function如何解决?
在Next.js中使用SunEditor出现
TypeError: core._resourcesStateChange is not a function错误的解决办法 问题说明
在Next.js项目中集成SunEditor富文本编辑器时触发TypeError: core._resourcesStateChange is not a function错误,但相同代码在纯React项目中可正常运行。
相关代码
编辑器组件(TextEditor2.js)
import React from "react"; import 'suneditor/dist/css/suneditor.min.css'; import dynamic from "next/dynamic"; const SunEditor = dynamic(() => import("suneditor-react"), { ssr: false, }); const TextEditor2 = props => { return ( <div> <SunEditor /> </div> ); }; export default TextEditor2;
页面文件(index.js)
import "suneditor/dist/css/suneditor.min.css"; import styles from "../styles/Home.module.css"; import TextEditor2 from "../components/TextEditor2"; export default function Home() { return ( <div className={styles.container}> <TextEditor2/> </div> ); }
错误截图:
解决步骤
1. 对齐依赖版本
该错误多因suneditor与suneditor-react版本不兼容导致,先卸载现有依赖,安装经过验证的兼容版本:
npm uninstall suneditor suneditor-react npm install suneditor@2.45.0 suneditor-react@3.6.0
2. 调整动态导入逻辑
修改编辑器组件的动态导入代码,明确获取默认导出,避免SSR相关问题:
import React from "react"; import dynamic from "next/dynamic"; const SunEditor = dynamic( () => import("suneditor-react").then(mod => mod.default), { ssr: false } ); const TextEditor2 = props => { return ( <div> <SunEditor /> </div> ); }; export default TextEditor2;
3. 统一全局CSS引入
将SunEditor的CSS统一在pages/_app.js中引入,避免重复引入引发冲突:
import 'suneditor/dist/css/suneditor.min.css'; import '../styles/globals.css'; function MyApp({ Component, pageProps }) { return <Component {...pageProps} />; } export default MyApp;
同时删除index.js中的import "suneditor/dist/css/suneditor.min.css";语句。
4. 清理缓存并重启项目
执行以下命令清除缓存,重新安装依赖后启动项目:
rm -rf .next node_modules package-lock.json npm install npm run dev
内容的提问来源于stack exchange,提问作者Berk KARASU
相关产品推荐
相关产品推荐

