Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue - Cannot use import statement outside a module

Tags:

vue.js

I´m trying to create a form. This form have a package.json with vue, axios and sweetalert.

"dependencies": {
  "axios": "^0.19.0",
  "vue": "^2.6.10",
  "vue-sweetalert2": "^2.1.1"
}

The JS is

<script>
  import Vue from 'vue';
  import VueSweetalert2 from 'vue-sweetalert2';
  import VueAxios from 'vue-axios';
  import axios from 'axios';
  import 'sweetalert2/dist/sweetalert2.min.css';
  Vue.use(VueSweetalert2, VueAxios, axios);
  var app = new Vue({
    el: '#app',
    methods: {
      guardar: function () {
        axios
          .get('ENDPONT')
          .then(response => {
            console.log(response);
            Vue.swal('Hello Vue world!!!');

          })
          .catch(function (error) {
            console.log(error);
            Vue.swal('Hello Vue world!!!');
          });
      }
    }
  });
</script>

The error is simple: Return 'Cannot use import statement outside a module'. I suppose that import is wrong, but im new in Vue and don't know what is the right way.

like image 666
El Hombre Sin Nombre Avatar asked Sep 27 '19 08:09

El Hombre Sin Nombre


People also ask

Can we use import statement outside a module?

The "Cannot use import statement outside module" error also occurs if you are trying to run your source files which contain ES6 module import / export syntax, instead of running your compiled files from your build directory. Make sure to run your compiled files from your build/dist directory only.

How do you solve the Cannot use import statement outside a module?

To solve the error "Cannot use import statement outside a module" in TypeScript, set the module option to commonjs in your tsconfig. json file and make sure to compile your TypeScript files (e.g. with ts-node ), and not to run them directly with node .

Can I use import in node?

The syntax for importing modules in ES6 looks like this. The reason for this error is that Node js doesn't support ES6 import directly. If you try to use import for importing modules directly in node js it will throw out that error. Do not worry about the error!


1 Answers

You're trying to use an import statement in a normal script tag, you can only do that with type="module" but I suspect you will run into many other issues if you continue down this path as many libraries are not built for use with ESM modules yet.

You'll be better off generating a project with https://cli.vuejs.org/ which will create a good starting base and compile your code and put it in a /build folder for you to deploy to your web hosting.

like image 195
Dominic Avatar answered Oct 13 '22 00:10

Dominic