我如何在不到15分钟内将 Unlayer 的拖拽式电子邮件编辑器添加到 Next.js

发布: (2026年1月3日 GMT+8 19:27)
7 min read
原文: Dev.to

Source: Dev.to

我在尝试 Unlayer 的 SDK

我尝试在 Next.js 应用中嵌入 Unlayer 的拖拽式邮件编辑器。该 SDK 能让你:

  • 在几分钟内导出 HTML 和 JSON 设计
  • 生成响应式、可直接投产的邮件 HTML
  • 避免常见的邮件客户端渲染怪癖

下面是我的发现以及为其他开发者准备的逐步指南。

我发现的

Unlayer 就像 用于电子邮件编辑的 Stripe ——它处理渲染细节,让你专注于应用。

关键特性

  • 客户端 JavaScript 包装器,嵌入拖拽编辑器
  • 生成 跨客户端兼容的 HTML,可直接用于生产
  • 导出 JSON(用于存储/编辑) 以及干净的 HTML(用于发送)
  • React 包装器 开箱即用
  • 无后端依赖——完全在浏览器中运行

步骤 1:安装

npm install react-email-editor

第 2 步:组件设置

'use client'

import { useRef } from 'react'
import dynamic from 'next/dynamic'

// Critical: Dynamic import with SSR disabled
// react-email-editor relies on browser APIs like `window`
// that aren't available during server‑side rendering
const EmailEditor = dynamic(
  () => import('react-email-editor').then((mod) => mod.EmailEditor),
  { ssr: false }
)

export default function Home() {
  const emailEditorRef = useRef(null)

  const exportHtml = () => {
    if (emailEditorRef.current) {
      emailEditorRef.current.editor.exportHtml((data: any) => {
        const { design, html } = data

        // Store JSON in your database for later editing
        console.log('Design JSON:', design)

        // Use HTML for sending emails
        console.log('Exported HTML:', html)

        // Download the HTML file
        const blob = new Blob([html], { type: 'text/html' })
        const url = URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = 'newsletter.html'
        link.click()
        URL.revokeObjectURL(url)
      })
    }
  }

  return (
    <>
      {/* Newsletter Builder UI */}
      <div style={{ height: 'calc(100vh - 60px)' }}>
        <EmailEditor ref={emailEditorRef} />
        <button onClick={exportHtml}>Export HTML</button>
      </div>
    </>
  )
}

障碍:SSR 与 Hydration

问题: 编辑器在服务器端渲染期间尝试访问 window,导致 hydration 错误。

解决方案: 使用 Next.js 的 dynamic 导入并设置 { ssr: false }。这会强制组件 仅在客户端 渲染,从而消除不匹配。

这种模式在 Next.js 项目中使用任何仅限浏览器的库时都很常见。

关键实现细节

细节说明
Ref ManagementuseRef 提供对编辑器实例的直接访问,以调用诸如 exportHtml() 的方法。
Height Calculation容器使用 calc(100vh - header height) 来填充剩余的视口空间。
Dual ExportSDK 返回 JSON(用于后续存储/编辑)和 HTML(发送至邮件服务)。

结果

在 ~15 分钟内,我完成了:

  • 一个功能完整的拖拽式电子邮件编辑器
  • 支持导出 JSONHTML 的功能
  • 响应式、可直接用于生产的邮件 HTML
  • 无需维护自定义渲染引擎

我喜欢的地方

原因
速度集成只用了几分钟,而不是几个月。
零后端完全在客户端运行。
简洁 API通过 ref 简单访问编辑器方法。
生产就绪输出HTML 在主流邮件客户端均可正常显示。

权衡

⚠️顾虑
SSR 处理需要使用动态导入 ({ ssr: false })。
包体积增加约 500 KB(对该功能而言可接受)。
样式对全高布局需要进行一些微调。

Build vs. Buy

When deciding whether to build a custom email editor or use Unlayer, consider the following comparison:

FactorBuild Your OwnUse Unlayer SDK
Initial Development Time4‑6 months (full‑time)15 min – 2 hrs (integration)
Email Client CompatibilityYou maintain the matrixHandled by Unlayer (tested on 50+ clients)
Responsive DesignWrite custom media queries & table layoutsBuilt‑in responsive engine
Dark‑Mode SupportCustom CSS & testing requiredAutomatic dark‑mode compatibility
Maintenance BurdenOngoing updates for client changesMinimal – SDK updates handle it
Custom Blocks / ExtensibilityFull control, but you build infrastructureBuilt‑in extensibility API (React/Vue components)
HTML Output QualityDepends on your implementationProduction‑ready, battle‑tested HTML
State ManagementBuild your own JSON schema & parserJSON schema provided, easy to store/load
Bundle SizeYou control it (but you build everything)~500 KB (includes full editor)
Learning CurveSteep – email HTML quirks, rendering enginesMinimal – React component with simple API
Time to Market6+ months to production‑readyShip in a sprint
Technical DebtHigh – legacy email HTML, browser quirksLow – abstracted away
Engineering Hours (Cost)~800‑1200 hrs initial + ongoing~2‑4 hrs integration + minimal maintenance
RiskHigh – unknown rendering issues in productionLow – proven in production by thousands

Bottom Line

If you need a quick, reliable, and maintainable email editor, Unlayer’s SDK is a solid choice. It removes the heavy lifting of email‑client quirks, lets you ship fast, and keeps the codebase lean. The only extra work is handling the client‑only nature of the library in a SSR environment like Next.js.

应用类型

构建(Build)如果:

  • 您拥有 6 + 个月 的时间和专职团队。
  • 您需要 极度定制,而 Unlayer 无法满足。
  • 邮件编辑是您的 核心产品(而不仅仅是一个功能)。

购买(Buy)Unlayer 如果:

  • 邮件编辑只是 一个功能,而不是您的产品。
  • 您需要 快速交付
  • 您希望将工程资源专注于 核心业务逻辑
  • 您需要 可靠的跨客户端兼容性,且不想承担维护负担。

对于大多数 SaaS 应用来说,计算结果很明确:购买
仅在渲染引擎维护上节省的时间,就足以让集成成本多次回本。

为什么不直接使用富文本编辑器?

你可能会问:“Why not use Tiptap or Quill?”

富文本编辑器非常适合文档,但在电子邮件布局上会出现问题。用户需要:

  • 多列布局
  • 响应式图片
  • 在各种客户端都能正常工作的按钮
  • 结构化模板

Unlayer 提供了一个 布局构建器,能够保证移动端友好的输出,并将设计保存为 JSON,以便进行编程编辑。

在生产环境中,你会:

  1. 将 JSON 设计 存储在数据库中。

  2. 使用以下方式加载已保存的设计:

    editor.loadDesign(designJson);
  3. 与你的邮件发送服务 集成。

  4. 为你的业务领域添加 自定义块(例如,产品列表、用户数据)。

Next.js Newsletter Builder

结论

Unlayer 抽象化了电子邮件渲染的复杂性。如果你的应用需要电子邮件编辑器,这个 SDK 值得评估。仅在渲染引擎维护上节省的时间就足以证明集成的价值。

有时最好的代码是你不必编写的代码。 😉

我期待着进一步探索并与大家分享!

Back to Blog

相关文章

阅读更多 »

修复 Next.js 中的水合错误

Hydration 错误的常见原因 浏览器/环境问题 - 浏览器扩展注入属性、密码管理器、广告拦截器、辅助功能工具 - Br...