使用本分步指南将 Tiptap 集成到你的 Next.js 项目中。
要求
创建项目(可选)
如果你已经有一个现有的 Next.js 项目,那也没问题,可以跳过此步骤。
在本指南中,我们将从头开始创建一个新的 Next.js 项目,命名为 my-tiptap-project。使用以下命令来设置所有需要的内容:
# 创建项目npx create-next-app my-tiptap-project# 进入项目目录cd my-tiptap-project
安装依赖
现在,我们已经设置好了标准的项目结构,可以开始安装 Tiptap 了!为此,我们需要安装以下三个包:@tiptap/react、@tiptap/pm 和 @tiptap/starter-kit,其中 StarterKit 包含了所有常见的扩展,能帮助你快速上手。
npm install @tiptap/react @tiptap/pm @tiptap/starter-kit
如果你已经完成了上面的步骤,现在可以使用 npm run dev 启动你的项目,并在你喜欢的浏览器中打开 http://localhost:3000/。如果你是在现有项目上进行操作,端口号可能会有所不同。
集成 Tiptap
要开始使用 Tiptap,你需要在应用中添加一个新组件。首先,创建一个名为 components/ 的目录。接下来,我们将在该目录下创建一个名为 Tiptap 的组件。在 components/Tiptap.jsx 文件中添加以下示例代码:
'use client'import { useEditor, EditorContent } from '@tiptap/react'import StarterKit from '@tiptap/starter-kit'const Tiptap = () => {const editor = useEditor({extensions: [StarterKit],content: '<p>Hello World! 🌎️</p>',})return <EditorContent editor={editor} />}export default Tiptap
将其添加到你的应用
现在,替换 pages/index.js 文件的内容,并使用 Tiptap 组件:
import Tiptap from '../components/Tiptap'export default function Home() {return <Tiptap />}
你现在应该可以在浏览器中看到 Tiptap 了。给自己点个赞吧!:)
在 Next.js 中使用 yjs
为了避免 Yjs was already imported. This breaks constructor checks and will lead to issues! 这个错误,请在 Next.js 配置文件中添加以下内容。你可能需要根据 node_modules/yjs 目录的位置调整路径,比如改为 ../node_modules/yjs 或 ../../node_modules/yjs。
const path = require('path')module.exports = {webpack: (config, { isServer }) => {if (!isServer) {// 确保所有的 'yjs' 导入解析为同一个实例config.resolve.alias['yjs'] = path.resolve(__dirname, 'node_modules/yjs')}return config},}
关于此问题的原始讨论和解决方案可以在 GitHub 上找到。
