Search code examples
typescriptvuejs2summernote

Summernote in typescript and vue


I want to use summernote in Vue component written in Typescript. But I get error:

Error TS2339 (TS) Property 'summernote' does not exist on type 'JQuery'.

My code looks like bellow:

import Vue from "vue";
import * as $ from "jquery";
require('summernote');

Then in template I have div:

<div ref="mysummernote" id="summernote"><p>Hello Summernote</p></div>

and in mounted() I have:

$('#summernote').summernote();

and this .summernote() method is marked as error with message like on the top. All code is written in typescript. To npm I added summernote package like on this website: https://www.npmjs.com/package/summernote


Solution

  • So this is how I married Vue + TypeScrypt + Summernote:

    Template:

    <html-editor height="200" :model.sync="yourFieldName"></html-editor>
    

    My package.json:

    {
      "devDependencies": {
        "typescript": "^3.4.5"
      },
      "dependencies": {
        "@types/bootstrap": "^4.3.1",
        "@types/jquery": "^3.3.29",
        "@types/select2": "^4.0.48",
        "@types/summernote": "^0.8.0"
      }
    }
    

    And here is my component:

    /// <reference path="../node_modules/@types/summernote/index.d.ts" />
    
    Vue.component("html-editor", {
        props : {
            model: {
                required: true
            },
            height: {
                type: String,
                default: "150"
            }
        },
        template: "#html-editor",
        mounted() {           
    
            let config : Summernote.Options = {
                height: this.height,
                followingToolbar: false, // that needs some tweak see below
                toolbar: [
                    ['style', ['bold', 'italic']]
                ],
                callbacks: {},   
            };            
    
            let vm = this;
            config.callbacks = {
                onInit: function () {
                    $(vm.$el).summernote("code", vm.model);
                },
                onChange: function () {
                    vm.$emit("update:model", $(vm.$el).summernote("code"));
                },
            };
            $(this.$el).summernote(config);
        }
    })
    

    I had to modify @types/summernote/index.d.ts:

    namespace Summernote {
        interface Options {
            ...
            followingToolbar?: boolean;
        }
    }
    

    (Pull request on the way)