How to make a dynamic import in Nuxt?

ghz 1years ago ⋅ 1043 views

Question

In my nuxt component I want to use the ace editor:

import Ace from "ace-builds/src-noconflict/ace"

when the component is mounted I am doing the following:

this.editor = Ace.edit...

Obviously the window is not defined on the server on page reload. But unfortunately I just can't find a solution to fix this issue.

Is there a way to import a package on the mounted() hook? I already tried

const Ace = require("ace-builds/src-noconflict/ace")

But that doesn't quite seem to work. Do you have any ideas to solve this issue?

I already tried to register a plugin plugins/ace.js:

import Vue from "vue"
import Ace from "ace-builds/src-noconflict/ace"
Vue.use(Ace)

registered it in nuxt.config.js:

plugins: [
    { src: "~/plugins/ace", mode: "client" }
],

But how do I use Ace in my component now? It is still undefined...


Answer

Since the error was thrown during the import statement, I'd recommended using dynamic imports as explained in my [other answer here](https://stackoverflow.com/questions/67518659/how-to- properly-load-bootstrap5s-masonry-into-nuxt/67522750#67522750).

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](https://github.com/egoist/vue-monaco#use-esm- version-with-webpack) 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](https://nuxtjs.org/docs/concepts/nuxt- lifecycle#client).


EDIT3: not directly related to the question, but some packages expose a component which is only available on the client-side (no SSR support), in those cases you could import the component only on the client side and easily prevent any other errors.