How to make a dynamic import in Nuxt?

Solution 1:

Nuxt Plugin

IMHO you were on the right track with the "plugin" solution. Only mistake was the Vue.use(Ace) part. This only works for vue plugins.

The plugin file could look somewhat like that:

import Ace from 'ace-builds/src-noconflict/ace'
import Theme from 'ace-builds/src-noconflict/theme-monokai'

export default ({ app }, inject) => {
  inject('ace', {
    editor: Ace,
    theme: Theme
  })
}

Then you could use this plugin and initiate the editor in a component this way:

<template>
  <div id="editor">
    function foo(items) {
    var x = "All this is syntax highlighted";
    return x;
    }
  </div>
</template>

<script>
export default {
  data () {
    return {
      editor: {}
    }
  },
  mounted () {
    this.editor = this.$ace.editor.edit('editor')
    this.editor.setTheme(this.$ace.theme)
  }
}
</script>

Solution 2:

Since the error was thrown during the import statement, I'd recommended using dynamic imports as explained in my other answer here.

async mounted() {
  if (process.client) {
    const Ace = await import('ace-builds/src-noconflict/ace')
    Ace.edit...
  }
},

From the official documentation: https://nuxtjs.org/docs/2.x/internals-glossary/context


EDIT: I'm not sure about Ace and it's maybe a drastic change but you may also give a look to vue-monaco which is elbow-to-elbow popularity wise (vanilla Monaco editor).

EDIT2: mounted actually only runs on the client so you could strip the process.client conditional. Meanwhile, I do let it here in case you want to run some logic in other hooks like created (which are run on both server + client). More info here.