avil13 / vue-sweetalert2

A convenient wrapper for sweetalert2.
https://avil13.github.io/vue-sweetalert2/
649 stars 75 forks source link

Import vue-sweetalert2 in SSR environment: Cannot use import statement outside a module #111

Closed phlegx closed 3 years ago

phlegx commented 3 years ago

Hi!

If I use vue-sweetalert2 with an SSR environment, I get this error:

node_modules/vue-sweetalert2/dist/index.js:8
    import Swal from 'sweetalert2';
    ^^^^^^

    SyntaxError: Cannot use import statement outside a module

Any idea how to solve this problem?

Version: 3.0.8 Vue: 2.6.12

avil13 commented 3 years ago

Hi! Are you using nuxt?

phlegx commented 3 years ago

No, I use UVue: https://universal-vue.github.io/docs/

avil13 commented 3 years ago

Thank you, I'll need to study the documentation and make corrections.

phlegx commented 3 years ago

I'm not sure, but could this be a solution? https://universal-vue.github.io/docs/guide/usage.html#use-ssr-non-compatible-libraries

avil13 commented 3 years ago

Is your project closed? Deploying a new project on a machine is expensive, so I could test everything on an example.

phlegx commented 3 years ago

It is closed. I have tried to add this config to my uvue.config.js, that imports vue-sweetalert2 only on spa.

// uvue.config.js

export default {
  plugins: [...],
  imports: [
    {
      src: '@/alerts',
      ssr: false,
    },
    {
      src: 'sweetalert2/dist/sweetalert2.min.css',
      ssr: false,
    },
  ],
}

And the js file:

// src/alerts.js

import Vue from 'vue'
import VueSweetalert2 from 'vue-sweetalert2'

Vue.use(VueSweetalert2)

But THIS DON'T WORK! This is not the right way.

I have solved the issue with (but is it the right way @avil13?):

// src/main.js

/* Instead of
 * import '@/alerts'
 */

/* process.client comes from Uvue. */

if (process.client) {
  require('@/alerts')
}

But also this is a bad way to solve the problem.

phlegx commented 3 years ago

@avil13 see this example app here: https://github.com/universal-vue/examples

phlegx commented 3 years ago

SOLVED WITH

/* vue.config.js */

module.exports = {
  transpileDependencies: [/vue-sweetalert2/]
}

Many thx to @chymz from Uvue!