背景:next.js 项目中 引入@wangeditor/editor 编辑器 在build时候,该依赖报错 ReferenceError: Element is not defined 导致无法成功发布

方案:利用 dynamic 动态引入该组件取消ssr渲染,改为cli端 渲染即可

应用:第三方插件不支持ssr渲染

报错

原来报错的代码就不写了,就是该富文本按照react的方式引入页面文件中,导致报错

image-20230410141322398.png

很明显 这个问题就是在打包的环境的中(node)中没有Element变量支持,因为这个变量在window上。

解决方案

//  /components/MyEdit.tsx
import React, { useEffect, useState } from 'react'
import { Editor, Toolbar } from "@wangeditor/editor-for-react";
import { IDomEditor, IEditorConfig, IToolbarConfig, SlateDescendant } from "@wangeditor/editor";
import '@wangeditor/editor/dist/css/style.css'

interface Props {
    html: any,
    setHtmlFn: any
}
export default function MyEditor(props: Props) {
    const { html, setHtmlFn } = props
    const [editor, setEditor] = useState<IDomEditor | null>(null); // TS 语法

    useEffect(() => {
        return () => {
          if (editor == null) return;
          editor.destroy();
          setEditor(null);
        };
      }, [editor]);
      
    const toolbarConfig: Partial<IToolbarConfig> = {}; // TS 语法
    const editorConfig: Partial<IEditorConfig> = {
        placeholder: "请输入内容...",
    };

    return (
        <div style={{ border: "1px solid #ccc", zIndex: 100 }}>
            <Toolbar
                editor={editor}
                defaultConfig={toolbarConfig}
                mode="default"
                style={{ borderBottom: "1px solid #ccc" }}
            />
            <Editor
                defaultConfig={editorConfig}
                value={html}
                onCreated={setEditor}
                onChange={(editor: any) => setHtmlFn(editor.getHtml())}
                mode="default"
                style={{ height: "500px", overflowY: "hidden" }}
            />
        </div>
    )
}
// 页面代码
...
import dynamic from 'next/dynamic'

const ReactWEditor = dynamic(import("../../../components/MyEditor"), {
  ssr: false,
  loading: () => <p>Loading ...</p>, 
});

...
const Page = () => {
 const [attachments, setAttachments] = useState<any[]>([]);
 const [html, setHtml] = useState("");
 return (
 <div>
     <ReactWEditor html={html} setHtmlFn={setHtml} />
 </div>
 
 )
}
  
  

按照上述代码配置后 ,该富文本插件的代码就会在 客户端 渲染该组件就不会有打包时候的问题了。

Last modification:April 10, 2023
如果觉得我的文章对你有用,请随意赞赏