從ckeditor5開始,默認的編譯版本,只提供了固定的功能,如果需要使用更多的特性,比如文字顏色,對齊,高亮等,則需要通過源代碼編譯的方式添加進去,以下說明下如何從源代碼方式編譯自定義的ckeditor5。
拷貝源代碼
官網教程 中,提供了從github上拷貝源代碼到本地開發的方式,但是由於國情,有概率下載失敗,這時候可以借助gitee的 從其他倉庫導入
功能,步驟如下
- 在 gitee.com 上新建一個倉庫,選擇
從其他倉庫導入
,倉庫地址為https://github.com/ckeditor/ckeditor5-build-classic.git
- 下載倉庫到本地
# 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>