클라이언트 전용 컴포넌트 플러그인으로 사용하기

최대 1 분 소요

문제

client에서만 사용 가능한 라이브러리는 nuxt server side에서 client 객체 참조를 하지 못해 오류가 발생.(navigator, window등)

해결 전에 알아야 할 것들

nuxt는 client사이드에서만 사용할 수 있는 플러그인들을 위해 nuxt.config.js에 옵션을 제공한다.

해결

WYSIWYG 에디터 사용을 위해 jquery로 만들어진 summernote를 적용해 보기로 한다.

  1. nuxt plugin 작성 (editor.js)
import 'summernote/dist/summernote-bs4'
import 'summernote/lang/summernote-ko-KR'
import 'summernote/dist/summernote-bs4.css'

import Vue from 'vue'

Vue.component( 'editor', {
  render: createElement => {
    return createElement( 'div' )
  },
  created() {},
  mounted() {
    $( this.$el )
      .summernote( {
        lang: 'ko-KR',
        width: '100%',
        height: 350,
        focus: false,
        callbacks: {
          onInit: () => {},
          onChange: () => {},
          onImageUpload: () => {},
          onMediaDelete: () => {}
        }
      } )
  }
} )
  1. nuxt.config.js
module.exports = {
  ...
  plugins: [
      ...
      {
        src: '~plugins/editor',
        ssr: false  // summernote가 navigator등 브라우저 객체를 사용하기 때문에 client에서만 사용
      }
      ...
  },
  build: {
    ...
    plugins: [
      new webpack.ProvidePlugin( {
        '$': 'jquery',      // jquery global
        'jQuery': 'jquery'  // jquery alias
      } )
    ]
    ...
  }
}

댓글남기기