使用本分步指南将 Tiptap 集成到你的 Next.js 项目中。

要求

  • 你的计算机上已安装 Node
  • 具备 React 的使用经验

创建项目(可选)

如果你已经有一个现有的 Next.js 项目,那也没问题,可以跳过此步骤。

在本指南中,我们将从头开始创建一个新的 Next.js 项目,命名为 my-tiptap-project。使用以下命令来设置所有需要的内容:

  1. # 创建项目
  2. npx create-next-app my-tiptap-project
  3. # 进入项目目录
  4. cd my-tiptap-project

安装依赖

现在,我们已经设置好了标准的项目结构,可以开始安装 Tiptap 了!为此,我们需要安装以下三个包:@tiptap/react@tiptap/pm@tiptap/starter-kit,其中 StarterKit 包含了所有常见的扩展,能帮助你快速上手。

  1. npm install @tiptap/react @tiptap/pm @tiptap/starter-kit

如果你已经完成了上面的步骤,现在可以使用 npm run dev 启动你的项目,并在你喜欢的浏览器中打开 http://localhost:3000/。如果你是在现有项目上进行操作,端口号可能会有所不同。

集成 Tiptap

要开始使用 Tiptap,你需要在应用中添加一个新组件。首先,创建一个名为 components/ 的目录。接下来,我们将在该目录下创建一个名为 Tiptap 的组件。在 components/Tiptap.jsx 文件中添加以下示例代码:

  1. 'use client'
  2. import { useEditor, EditorContent } from '@tiptap/react'
  3. import StarterKit from '@tiptap/starter-kit'
  4. const Tiptap = () => {
  5. const editor = useEditor({
  6. extensions: [StarterKit],
  7. content: '<p>Hello World! 🌎️</p>',
  8. })
  9. return <EditorContent editor={editor} />
  10. }
  11. export default Tiptap

将其添加到你的应用

现在,替换 pages/index.js 文件的内容,并使用 Tiptap 组件:

  1. import Tiptap from '../components/Tiptap'
  2. export default function Home() {
  3. return <Tiptap />
  4. }

你现在应该可以在浏览器中看到 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

  1. const path = require('path')
  2. module.exports = {
  3. webpack: (config, { isServer }) => {
  4. if (!isServer) {
  5. // 确保所有的 'yjs' 导入解析为同一个实例
  6. config.resolve.alias['yjs'] = path.resolve(__dirname, 'node_modules/yjs')
  7. }
  8. return config
  9. },
  10. }

关于此问题的原始讨论和解决方案可以在 GitHub 上找到。