Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

vue.js - How to make a dynamic import in Nuxt?

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.browser) {
    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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.5k users

...