如何从 GrapesJS 导出 HTML 和 CSS(2026)

从 GrapesJS 导出生产 HTML 和 CSS:getHtml/getCss,构建完整文档,导出命令,以及可下载的 ZIP。

DevFuture Development
DevFuture Development
2026年4月11日3 个月前
阅读约 3 分钟6 次浏览

你需要的两种方法

GrapesJS 将当前页面以字符串 editor.getHtml() 形式暴露:对于 标记和 editor.getCss() 样式。其他所有东西——满了 文档、下载、ZIP——这些都是建立在这两者的基础上。

1. 阅读HTML和CSS

const html = editor.getHtml();
const css = editor.getCss();

2. 整理完整文档

const doc = `<!doctype html>
<html>
  <head><meta charset="utf-8"><style>${css}</style></head>
  <body>${html}</body>
</html>`;

// Store `doc`, or render it server-side.

3. 显示出口模态

// Built-in: opens a modal with the current HTML/CSS for copy-paste.
editor.runCommand('export-template');

4. 下载ZIP(index.html + style.css)

import grapesjs from 'grapesjs';
import exportPlugin from 'grapesjs-plugin-export';

const editor = grapesjs.init({
  container: '#gjs',
  plugins: [exportPlugin],
  pluginsOpts: { 'grapesjs-plugin-export': {} },
});

// Trigger the ZIP download:
editor.runCommand('gjs-export-zip');

提示:控制包含哪些CSS

// e.g. include rules even for components not currently on the canvas
const css = editor.getCss({ keepUnusedStyles: true });

小贴士

Exported code and markup on a screen
电子邮件的内联CSS;保留未使用的样式作为可重复使用的模板。

将导出地址与目的地匹配。对于电子邮件,可以内联使用 CSS(通过类似 juice的工具,或者用 MJML 预设构建),因为大多数客户端会忽略 <style> 块。对于可复用模板,请传递 getCss({ keepUnusedStyles: true }) ,确保当前不在画布上的组件规则得以保留。ZIP 导出 grapesjs-plugin-export 工具很适合交接,但对于程序化出版,则需要直接读取 getHtml()/getCss() 存储。无论目标是什么,如果编辑者对不信任的用户开放,发布前应对标记进行净化。

前提条件

你需要一个正在运行的GrapesJS编辑器。以下内容基于两种方法—— editor.getHtml() 以及 editor.getCss() —— 返回字符串 你可以存储、渲染或打包。

控制包含哪些CSS

getCss() 接受各种选项。保留当前未在 canvas(对可复用模板非常有用),或通过特定组件范围:

const css = editor.getCss({ keepUnusedStyles: true });

导出邮件(内联CSS)

大多数邮件客户端会忽略 <style> 块,所以在CSS之前内联 CSS 发送——要么用MJML预设构建,要么通过 内联插件如下 juice

import juice from 'juice';
const inlined = juice(`<style>${editor.getCss()}</style>${editor.getHtml()}`);

下载压缩包

import exportPlugin from 'grapesjs-plugin-export';
const editor = grapesjs.init({ container: '#gjs', plugins: [exportPlugin] });
editor.runCommand('gjs-export-zip');   // index.html + style.css

程序化地持续执行导出

关于发布,直接阅读字符串并发布到后台,而不是 依赖下载——存储 htmlcss, 和 完整 project 所以页面既渲染得很快,又能在编辑器中重新打开。

最佳实践

导出地址与目的地匹配:邮件内联CSS,完整文档 独立页面,CMS的独立html/css列。Sanitise 出口加价之前 如果编辑对不受信任的用户开放,就发布。把你存储的项目版本改成这样 你可以回滚错误的编辑。

下一步

存储管理器后端 引导,或者将导出为可重复使用的包装 自定义插件。浏览 GrapesJS 插件 GJS。市场

常见问题

我该如何从 GrapesJS 中提取 HTML 和 CSS?

editor.getHtml() 并返 editor.getCss() 还加价 以及风格作为弦乐。

我该如何让用户下载ZIP?

添加 grapesjs-plugin-export 并运行 gjs-export-zip 命令下载index.html加style.css。

getCSS 只包含已使用样式吗?

默认情况下,它返回当前页面的管理样式;通行选项如 keepUnusedStyles 改变这种状况。

发布于 2026年4月11日
更新于 2026年6月27日
🔌 GJS.Market

在寻找 GrapesJS 插件吗?

超过 100 款精选插件、预设与模板 —— 由社区精挑细选并持续维护。

分享本文TwitterFacebookLinkedIn

更多来自 DevFuture Development

发现更多精彩文章,及时获取最新内容。

查看全部文章

来自 DevFuture Development 的付费插件

由该作者精心打造的精选付费插件。

访问店铺 →