简体   繁体   中英

Cannot use import statement outside a module using nuxtjs

I am trying to use vue-agile carousel, I can install and get it to run without any issues right after i install it, i am using NUXT, but after restarting my server i keep getting this error and can not find any solution for it

<template>
  <div>
    <agile>
      <div class="slide">
        <img src="/img/img2.jpg" alt="" />
      </div>
      <div class="slide">
        <img src="/img/img1.jpg" alt="" />
      </div>
    </agile>
  </div>
</template>
<script >
import { VueAgile } from "vue-agile";
export default {
  name: "",
  layout: "",
  middleware: [],
  data() {
    return {};
  },
  components: {
    agile: VueAgile,
  },
  
};
</script>

在此处输入图像描述

在此处输入图像描述

Did you checked the documentation abouthow to use this plugin in Nuxt instead of a regular Vue?

plugins/vue-agile.js

import Vue from 'vue'
import VueAgile from 'vue-agile'

Vue.use(VueAgile)

nuxt.config.js

export default {
    plugins: ['~/plugins/vue-agile', mode: 'client']
}

To use component without SSR use the client-only component:

<client-only placeholder="Loading...">
    <agile>...</agile>
</client-only>

EDIT : Add Shreerang's suggestion (comment below).

Sergio's answer above is mostly accurate, but needs a small tweek.

The nuxt.config.json config needs the following update. No build config is required.

plugins: [
    { src: '~/plugins/vue-agile', mode: 'client' }
]

Add type="module" in your script tag

<script type="module">
import { VueAgile } from "vue-agile";
export default {
  name: "",
  layout: "",
  middleware: [],
  data() {
    return {};
  },
  components: {
    agile: VueAgile,
  },
  
};
</script>

You need to mark vue-agile to be transpiled in order to work on the server part (SSR).

nuxt.config.js :

...
  build: {
    transpile: [/vue-agile/]

  }
...

As Brahim mentioned - I fixed it with:

build: {        
    transpile: ['npm-package-name'],   
},

They mentioned this here - https://nuxtjs.org/docs/directory-structure/plugins/

As example, in my case that was:

['vue-picture-swipe']

from official Nuxt.js docs, they said.

If you get an Cannot use import statement outside a module error, you may need to add your package to the build > transpile option in nuxt.config.js for webpack loader to make your plugin available.

Example

module.exports = {
  build: {
    transpile: ['vue-agile']
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM