はじめに
Nuxt(SSR)でリッチテキストを使いたいと思い、いろいろ調べていた際に出会ったCKEditorについて、導入に時間がかかりましたので、導入方法をこちらに記載しておきます。
間違いや認識違いなどございましたらご指摘頂けますと幸いです。
環境
- Nuxt 2.15.8(SSR)
- veutify 2.6.12
- CKEdtitor5
結論
まずは結論です。
ckeditorはインストールしておいてください。
※下記はvue2なので、適宜変更してください。
では改めて
import Vue from 'vue';
import Ckeditor from '../components/Ckeditor.vue';
Vue.component('Ckeditor', Ckeditor);
<template>
<div class="ckeditor">
<ckeditor
v-model="editorData"
:editor="editor"
:config="editorConfig"
class="ckeditor"
>
</ckeditor>
</div>
</template>
<script>
import CKEditor from '@ckeditor/ckeditor5-vue2'
import ClassicEditor from '@ckeditor/ckeditor5-build-classic';
export default {
name: 'CkEditor',
components: { ckeditor: CKEditor.component },
props: {
value: {
type: String,
default: ''
}
},
data() {
return {
editor: ClassicEditor,
editorData: '<p>Content of the editor.</p>',
editorConfig: {
toolbar: [ 'heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', 'blockQuote' ],
heading: {
options: [
{ model: 'paragraph', title: '見出し', class: 'ck-heading_paragraph' },
{ model: 'heading1', view: 'h1', title: '大見出し', class: 'ck-heading_heading1' },
{ model: 'heading2', view: 'h2', title: '小見出し', class: 'ck-heading_heading2' }
]
},
},
}
},
};
</script>
<!-- 下記はわかりやすく表示するためなので、不要 -->
<style lang="scss" scoped>
.ckeditor {
width: 100%;
max-width: 800px;
height: 500px;
margin: 0 auto;
border: 1px solid #9E9E9E;
}
</style>
plugins: [
{ src: '~/plugins/ckeditor.js', mode: 'client'},
],
// 省略
build: {
// CkEditor
plugins: [
// If you set ssr: true that will cause the following error. This error does not affect the operation.
// ERROR [CKEditorWebpackPlugin] Error: No translation has been found for the zh language.
new CKEditorWebpackPlugin({
// See https://ckeditor.com/docs/ckeditor5/latest/features/ui-language.html
// language: "ja",
additionalLanguages: 'all',
addMainLanguageTranslationsToAllAssets: true,
})
],
// If you don't add postcss, the CKEditor css will not work.
postcss: CKEditorStyles.getPostCssConfig({
themeImporter: {
themePath: require.resolve("@ckeditor/ckeditor5-theme-lark")
},
minify: true
}),
},
<template>
<client-only>
<Ckeditor v-model="text" />
</client-only>
</template>
補足
まず大前提として、SSRではサーバー側でロードされてしまうので、クライアント側のみのものに対してエラーになることが多いです。(ニュアンスで意味を汲み取ってください)
それを回避する術が必要不可欠。
こちらのGithubにも記載がございますが、間違いなく下記のエラーにぶち当たります。
window is not defined
何度も君のことを見たよ。。。
これはプラグインファイルと対象のpageとcomponentsをclientのみで表示することができれば問題ないはず。です。
このエラーさえ表示させなければこっちのものと言っても過言ではありません!
そのために、
// clientのみに
{ src: '~/plugins/ckeditor.js', mode: 'client'}
// cilentのみに
<client-only>
<Ckeditor v-model="text" />
</client-only>
エラーが表示されなくなればあとはプラグインを追加したり、色々できると思います。
私はこちらのプラグインを入れて、下記のようにできました👍
@ckeditor/ckeditor5-build-balloon
まとめ
SSRを使う際は、クライアントサイドでしか動かないプラグインが存在すること
どうすればクライアントだけで使用できるのか。それをコードに落とし込むこと。
とても大切だと思いました。。
おわり