Import npm package into a Vue.js Single File component

523 views Asked by At

I would like to use Jodit in a SFC, but I am not sure how this is supposed to be done. I realized there is a wrapper (jodit-vue), but for educational purposes, I would like to know how it's done without it. I created a Vue CLI project with default presets, and all I changed is the App.vue:

<template>
  <div id="app">
    <textarea id="editor" name="editor"></textarea>
  </div>
</template>

<script>
import "../node_modules/jodit/build/jodit.min.js"

export default {
  name: 'App',
  created(){
    let editor = new Jodit('#editor');
    editor.value = '<p>start</p>';
  }
}
</script>

<style>
@import "../node_modules/jodit/build/jodit.min.css" ;
</style>

This produces the error: error 'Jodit' is not defined no-undef, and if I change the import to:

import Jodit from "../node_modules/jodit/build/jodit.min.js"

Then the compilation is fine, but the browser console says:

vue.runtime.esm.js?2b0e:1888 TypeError: _node_modules_jodit_build_jodit_min_js__WEBPACK_IMPORTED_MODULE_0___default.a is not a constructor

Admittedly, I am new to all of this, but pointing me to the right direction is appreciated.

1

There are 1 answers

0
tony19 On BEST ANSWER

The jodit module exports the Jodit constructor, so your component would import it like this:

import { Jodit } from 'jodit'

You'd also need the Jodit styles, which could be imported like this:

import 'jodit/build/jodit.min.css'

To create a Jodit instance, we need to provide an element or selector to an existing <textarea>. The Vue component's elements are available in the mounted() lifecycle hook (not in the created() hook), so that's where we would initialize:

export default {
  mounted() {
    const editor = new Jodit('#editor')
    editor.value = '<p>start</p>'
  },
}

demo