自定义ckeditor5

从ckeditor5开始,默认的编译版本,只提供了固定的功能,如果需要使用更多的特性,比如文字颜色,对齐,高亮等,则需要通过源代码编译的方式添加进去,以下说明下如何从源代码方式编译自定义的ckeditor5。

拷贝源代码

官网教程 中,提供了从github上拷贝源代码到本地开发的方式,但是由于国情,有概率下载失败,这时候可以借助gitee的 从其他仓库导入 功能,步骤如下

  1. 在 gitee.com 上新建一个仓库,选择从其他仓库导入,仓库地址为 https://github.com/ckeditor/ckeditor5-build-classic.git
  2. 下载仓库到本地
# https://gitee.com/somebugs/ckeditor5-build-classic 是我自己的gitee仓库地址

git clone -b stable https://gitee.com/somebugs/ckeditor5-build-classic

# 安装依赖
npm i

自定义编辑器

下载下来的源代码,已经配置好了默认的功能,只需要对其进行增减即可。

功能

以添加字体, 对齐, 高亮三个功能为例, 需要先安装对应的插件,

npm i @ckeditor/ckeditor5-font @ckeditor/ckeditor5-alignment @ckeditor/ckeditor5-highlight -D

需要编辑 src/ckeditor.js

// src/ckeditor.js

// Font      包含了字体,文字颜色,文字背景色三个功能
// Highlight 包含了字体高亮和背景高亮
import Font from '@ckeditor/ckeditor5-font/src/font';
import Alignment from '@ckeditor/ckeditor5-alignment/src/alignment'; 
import Highlight from '@ckeditor/ckeditor5-highlight/src/highlight';

ClassicEditor.builtinPlugins = [
  ...// 原有的插件
  Font,
  Alignment,
  Highlight,
];

ClassicEditor.defaultConfig = {
  toolbar: {
    items: [
      ...// 原有配置
      'alignment',
      '|',
      'fontSize', 
      'fontFamily', 
      'fontColor', 
      'fontBackgroundColor',
      'highlight',
      '|',
      ...// 原有配置
    ]  
  }
}

然后执行以下命令,即可在build目录下生成新的ckeditor.js文件

npm run build

语言

注意:自定义方式构建出的ckeditor不支持官方的语言包。

模板默认内置的语言是英语,如果需要修改默认的语言为中文,则需要同时修改
webpack.config.js/src/ckeditor.js 文件中的 language 配置:

language: 'zh-cn'

在打包的同时,会在 build 文件夹下面生成 translations 文件夹,里面自动翻译了非常多的语言(默认语言除外),在使用中如果需要使用其他语言,直接引入对应的语言文件即可。

使用

默认会生成umd方式 的js文件,可以直接使用,也可以通过ES6模块方式导入使用。直接使用的变量名依然是 window.ClassicEditor

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>CKEditor 5 – classic editor build – development sample</title>
    <style>
        body {
            max-width: 800px;
            margin: 20px auto;
        }
  </style>

</head>
<body>

<h1>CKEditor 5 – classic editor build – development sample</h1>

<div id="editor">
    <h2>Sample</h2>

    <p>This is an instance of the <a href="https://ckeditor.com/docs/ckeditor5/latest/builds/guides/overview.html#classic-editor">classic editor build</a>.</p>

    <figure class="image">
        <img src="../tests/manual/sample.jpg" alt="Autumn fields" />
    </figure>

    <p>You can use this sample to validate whether your <a href="https://ckeditor.com/docs/ckeditor5/latest/builds/guides/development/custom-builds.html">custom build</a> works fine.</p>
</div>

<script src="../build/translations/en.js"></script>
<script src="../build/translations/zh.js"></script>
<script src="../build/ckeditor.js"></script>

<script>
    ClassicEditor.create( document.querySelector( '#editor' ), {
    language: 'en'
  } )
        .then( editor => {
            window.editor = editor;
        } )
        .catch( err => {
            console.error( err.stack );
        } );
</script>

</body>
</html>

猜你喜欢

转载自www.cnblogs.com/small-coder/p/10984554.html