221110 TIL | 리액트 프로젝트에 Froala Editor 라이브러리 적용하기

오늘 한 일

  • Froala Editor

Froala Editor 라이브러리 추가

⭐ 즐겨찾기

라이브러리 설치

  • yarn add react-froala-wysiwyg
  • yarn add froala-editor : 라이브러리 사용을 위해 추가

컴포넌트 생성

import React, { useState } from 'react';
/** 에디터 기본 설정 */
import FroalaEditor from 'react-froala-wysiwyg';
import 'froala-editor/js/froala_editor.pkgd.min.js';
import 'froala-editor/css/froala_editor.pkgd.min.css';
import 'froala-editor/css/froala_style.min.css';
import '@fortawesome/fontawesome-free/css/fontawesome.css';
/** 워드, 엑셀 붙여넣기 */
import 'froala-editor/js/plugins/word_paste.min.js';
/** 색상 추가 */
import 'froala-editor/js/plugins/colors.min.js';
/** 파일 업로드 */
import 'froala-editor/js/plugins/file.min.js';
/** 단락 줄 높이 */
import 'froala-editor/js/plugins/line_height.min.js';
/** 테이블 */
import 'froala-editor/js/plugins/table.min.js';
import 'froala-editor/css/plugins/table.min.css';
/** URL 추가 */
import 'froala-editor/js/plugins/url.min.js';

type Props = {

}

const config = {
    height: '650px',
    language: 'ko',
    events: {
        'focus' : function() {
            console.log("focus event", this);
        }
    },
    // 빠른 편집 팝업 창 z-index 값 필수
    zIndex: 9999,
}

function FroalaEditorComponent(props: Props): JSX.Element {

    const [editor, setEditor] = useState<FroalaEditor | null>(null);

    const handleEditorChange = (editor:any) => {
        setEditor(editor);
        // 에디터 안 HTML 내용이 출력 됨.
        console.log(`handleEditorChange` + editor);
    }

    return (
        <>
            <div>
                <FroalaEditor 
                    tag="textarea"
                    config={config}
                    onModelChange={handleEditorChange}
                />
            </div>
        </>
    );
}

export default FroalaEditorComponent;

워드, 엑셀 붙여넣기 플러그인 설치

https://froala.com/word-paste-plugin/

import 'froala-editor/js/plugins/word_paste.min.js';

버튼 커스텀

  • yarn add froala-editor
  • 모듈에 타입 지정되어 있지 않아 오류 발생.

    https://github.com/froala/wysiwyg-editor/issues/2369

    • 사용자 지정 타입 추가
    • /node_modules/@types/froala-editor/index.d.ts 타입 파일 생성
    • d.ts 파일이란?

      💡

      • d.ts 파일은 기존 자바스크립트로 작성된 서드파티 모듈을 타입스크립트 환경에서도 사용할 수 있도록 타입만 정리한 파일이다.
      • 해당 파일이 없다면 Javascript 기반 라이브러리는 TS 환경에서 타입이 지정되지 않아 파일을 정상적으로 인지하지 못하는 상황이 발생한다.
      • @types가 붙은 모듈들이 타입만 선언된 모듈이다.
        • tsconfig에서 declaration 속성에 true를 준다면 TS 파일을 JS로 컴파일하는 과정에서 JS파일과 함께 d.ts 파일을 생성한다고 함.
      • 패키지 모듈을 설치하면 @types/module-name 에 type 이 지정되어 있는데 없을 때도 많다. 아쉬우면 필요한만큼만 만들어 쓰면 된다.
      • 구현이 없는 선언을 ambient라고 하는데 이런 선언들이 d.ts 파일에 들어가게 된다.
      • 자세한 정보 참고

      [TypeScript] .d.ts파일이 뭘까?

  • 요약 : 앞으로도 라이브러리 설치할 때 타입이 없으면 필요한 파일만 만들어서 사용하자.

버튼 변경 테스트

// 굵게 아이콘을 플러스로 변경
FroalaEditor.DefineIcon('bold', {FA5NAME: 'plus', template: 'font_awesome_5r'});

적용 방법

// 기본 font-awesome 사용. 사용자 템플릿 지정 가능.
FroalaEditor.DefineIconTemplate('eden_ui', '<i class="eui-icon eui-icon-[NAME]"></i>');

// edenui 아이콘으로 변경
FroalaEditor.DefineIcon('bold', {NAME: 'bold', template: 'eden_ui'});
FroalaEditor.DefineIcon('italic', {NAME: 'italic', template: 'eden_ui'});
FroalaEditor.DefineIcon('underline', {NAME: 'underline', template: 'eden_ui'});

// 이미지 아이콘 생성
FroalaEditor.DefineIcon('imageIcon', {SRC: 'https://upload.wikimedia.org/wikipedia/commons/thumb/6/6e/Golde33443.jpg/280px-Golde33443.jpg', ALT: 'Image button', template: 'image'});
FroalaEditor.RegisterCommand('**imageButton**', {
    title: 'puppy',
    icon: 'imageIcon'
		// 이벤트 설정 가능
});

const config = {
		... // 생략
		// 툴바에 보여줄 버튼 추가
		**toolbarButtons : {
        'moreText': {
          'buttons': ['imageButton', 'bold', 'italic', 'underline', 'strikeThrough', 'subscript', 'superscript', 'fontFamily', 'fontSize', 'textColor', 'backgroundColor', 'inlineClass', 'inlineStyle', 'clearFormatting'],
          'buttonsVisible': 5,** // 5개 이상은 더보기 버튼에서 보여주도록 설정
        **},
        'moreParagraph': {
          'buttons': ['alignLeft', 'alignCenter', 'formatOLSimple', 'alignRight', 'alignJustify', 'formatOL', 'formatUL', 'paragraphFormat', 'paragraphStyle', 'lineHeight', 'outdent', 'indent', 'quote']
        },
        'moreRich': {
          'buttons': ['insertLink', 'insertImage', 'insertVideo', 'insertTable', 'emoticons', 'fontAwesome', 'specialCharacters', 'embedly', 'insertFile', 'insertHR']
        },
        'moreMisc': {
          'buttons': ['undo', 'redo', 'fullscreen', 'print', 'getPDF', 'spellChecker', 'selectAll', 'html', 'help'],
          'align': 'right',
          'buttonsVisible': 2
      
        }
      
      }**
}

테마 설정

  • css import 후 config.theme = [dark, gray, royal] 입력