vue3 code editor 라이브러리 사용하기

sunlog·2023년 3월 20일
0

개발 목적

  • 현재 프로젝트에서 코드 에디터 관련 기능을 제공해야 함. -> 미리 실험적으로 구현 가능 여부와 제공할 기능 범위 파악이 필요하여 기본적인 기능 구현이 필요했음. 기본적인 기능 구현 외에도 기능을 추가하여 공통 컴포넌트화 하여 사용 할 수 있음.

사용한 라이브러리

사용 환경

  • typescript
  • vite
  • vue3

설치

npm i vue3-ace-editor --save

사용 방법

1. config파일 작성

  • ace-editor에서 구문 체크나 검색 박스 등의 추가 기능을 사용하기 위해서는 config 파일을 import 해서 사용해야 한다. 따라서, config폴더 하위에 aceConfig파일을 생성한다.
    import ace from 'ace-builds';
    
    import modeJsonUrl from 'ace-builds/src-noconflict/mode-json?url';
    ace.config.setModuleUrl('ace/mode/json', modeJsonUrl);
    
    import modeJavascriptUrl from 'ace-builds/src-noconflict/mode-javascript?url';
    ace.config.setModuleUrl('ace/mode/javascript', modeJavascriptUrl);
    
    import modeHtmlUrl from 'ace-builds/src-noconflict/mode-html?url';
    ace.config.setModuleUrl('ace/mode/html', modeHtmlUrl);
    
    import modeYamlUrl from 'ace-builds/src-noconflict/mode-yaml?url';
    ace.config.setModuleUrl('ace/mode/yaml', modeYamlUrl);
    
    import themeGithubUrl from 'ace-builds/src-noconflict/theme-github?url';
    ace.config.setModuleUrl('ace/theme/github', themeGithubUrl);
    
    import themeChromeUrl from 'ace-builds/src-noconflict/theme-chrome?url';
    ace.config.setModuleUrl('ace/theme/chrome', themeChromeUrl);
    
    import themeMonokaiUrl from 'ace-builds/src-noconflict/theme-monokai?url';
    ace.config.setModuleUrl('ace/theme/monokai', themeMonokaiUrl);
    
    import workerBaseUrl from 'ace-builds/src-noconflict/worker-base?url';
    ace.config.setModuleUrl('ace/mode/base', workerBaseUrl);
    
    import workerJsonUrl from 'ace-builds/src-noconflict/worker-json?url';
    ace.config.setModuleUrl('ace/mode/json_worker', workerJsonUrl);
    
    import workerJavascriptUrl from 'ace-builds/src-noconflict/worker-javascript?url';
    ace.config.setModuleUrl('ace/mode/javascript_worker', workerJavascriptUrl);
    
    import workerHtmlUrl from 'ace-builds/src-noconflict/worker-html?url';
    ace.config.setModuleUrl('ace/mode/html_worker', workerHtmlUrl);
    
    import workerYamlUrl from 'ace-builds/src-noconflict/worker-yaml?url';
    ace.config.setModuleUrl('ace/mode/yaml_worker', workerYamlUrl);
    
    import snippetsHtmlUrl from 'ace-builds/src-noconflict/snippets/html?url';
    ace.config.setModuleUrl('ace/snippets/html', snippetsHtmlUrl);
    
    import snippetsJsUrl from 'ace-builds/src-noconflict/snippets/javascript?url';
    ace.config.setModuleUrl('ace/snippets/javascript', snippetsJsUrl);
    
    import snippetsYamlUrl from 'ace-builds/src-noconflict/snippets/yaml?url';
    ace.config.setModuleUrl('ace/snippets/javascript', snippetsYamlUrl);
    
    import snippetsJsonUrl from 'ace-builds/src-noconflict/snippets/json?url';
    ace.config.setModuleUrl('ace/snippets/json', snippetsJsonUrl);
    
    import 'ace-builds/src-noconflict/ext-language_tools';
    import 'ace-builds/src-noconflict/ext-searchbox';
    ace.require('ace/ext/language_tools');
    ace.require('ace/ext/searchbox');
    
    export default ace;

2. code editor 컴포넌트 생성

  1. CodeEditor.vue 파일을 생성한다. (이름 마음대로 생성)

  2. config 파일과 vue3-ace-editor 라이브러리를 import 한다.

    <script setup lang="ts">
    import { ref, onMounted } from 'vue';
    import '@config/aceConfig'; // 코드 에디터 설정 (필요시 추가 설정 후 임포트해서 사용)
    import { VAceEditor } from 'vue3-ace-editor';
  3. 코드 에디터로 표시할 language와 테마 등 옵션과 변수를 설정한다. (props로 부모 컴포넌트에서 값을 받아오는 방법으로 수정 가능함)

    const lang = 'json'; // json / html / yaml / javascript 등등
    const theme = 'github'; // monokai / github 등등
    
    const options = {
      cursorStyle: 'wide',
      useWorker: true,
      enableBasicAutocompletion: true,
      enableSnippets: true,
      enableLiveAutocompletion: true,
      highlightSelectedWord: true,
    };
    
    let edit = ref<typeof VAceEditor | null>(null);
    let value = ref<string>('');
  4. 코드 에디터 Init 함수와 Json을 불러오는 Init 함수를 작성한다. (해당 예시에선 vue의 package.json 파일을 불러온다.)

    // 코드 에디터 Init 함수
    function editorInit(editor: typeof VAceEditor) {
      edit.value = editor;
    }
    
    // 예시 Json Init 
    async function initJson() {
      value.value = '';
      value.value = (await import('../../../../package.json?raw')).default;
    }
  5. Vue의 onMounted 사이클에서 InitJson 함수를 호출하는 코드를 작성한다.

    onMounted(() => {
      initJson();
    });
  6. 템플릿 태그 안에 코드 에디터 태그를 사용하여 코드 에디터를 화면에 표시한다.

    <template>
    	<div class="code-wrap">
              <v-ace-editor
                v-model:value="value"
                :lang="lang"
                :theme="theme"
                :options="options"
                :readonly="true"
                :wrap="true"
                :default="true"
                :min-lines="20"
                :max-lines="30"
                @init="editorInit"
              />
    	</div>
    </template>

3. 단어 검색 및 코드 펼치기 접기 기능 추가

  1. 검색창, 이전/다음 버튼 UI와 펼치기 접기 버튼을 추가로 만들고 code editor에서 제공하는 아래 함수들을 이용하여 기능을 추가 제공 할 수 있다.

    // 코드 검색
    function onFind(keyword) {
      if (edit.value) {
        edit.value.findAll(keyword, {
          backwards: false,
          wrap: true,
          caseSensitive: false,
          wholeWord: false,
          regExp: true,
        });
      }
    }
    
    // 다음 검색
    function onNext() {
      if (edit.value) {
        edit.value.findNext();
      }
    }
    // 이전 검색
    function onPrevious() {
      if (edit.value) {
        edit.value.findPrevious();
      }
    }
    //펼치기
    function onFold() {
      if (edit.value) {
        edit.value.session.expandFolds(edit.value.session.getAllFolds());
      }
    }
    // 접기
    function onUnFold() {
      if (edit.value) {
        edit.value.session.foldAll();
      }

참고

0개의 댓글