5

I'm trying to import a library of the Vuelidate plugin into my newsletter.vue.js component.

But this import returns an error: Uncaught SyntaxError: Unexpected identifier

How can I import this into my vue.js component?

First to all, I´m using webpack and call first Vuelidate:

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');


window.Vue = require('vue');

import BootstrapVue from 'bootstrap-vue'
import Vuelidate from 'vuelidate'

Vue.use(BootstrapVue)
Vue.use(Vuelidate)

/**
 * The following block of code may be used to automatically register your
 * Vue components. It will recursively scan this directory for the Vue
 * components and automatically register them with their "basename".
 *
 * Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
 */

// const files = require.context('./', true, /\.vue$/i)
// files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default))

//Vue.component('example-component', require('./components/ExampleComponent.vue').default);

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

const app = new Vue({
});

window.onload = function(){
    app.$mount('#app');
}

Then I see that I have to import 'vuelidate/lib/validators' into the component in order to use it.

Like this example.

The problem is that I can't do an import inside my component vue, it always gives me error.

This is the code of my component:

import validators from 'vuelidate/lib/validators';//this return me error

Vue.component('newsletter', {

    template :  '<div>\
      <b-form @submit="onSubmit">\
        \
          \
        <b-form-group id="exampleInputGroup2" label="Food" label-for="exampleInput2">\
          <b-form-select\
            id="exampleInput2"\
            :options="foods"\
            :state="$v.form.food.$dirty ? !$v.name.$error : null"\
            v-model="form.food"\
          />\
  \
          <b-form-invalid-feedback id="input2LiveFeedback">\
            This is a required field\
          </b-form-invalid-feedback>\
        </b-form-group>\
  \
        <b-button type="submit" variant="primary" :disabled="$v.form.$invalid">Submit</b-button>\
      </b-form>\
    </div>',

    props : ['route_post'],

    data: function()
    {
        return {
            foods: ['apple', 'orange'],
            form: {}
          }
    },  

    validations: {
      form: {
        name: {
          required: validators.required,
          minLength: validators.minLength(3)
        }
      }
    },

});
Antonio Morales
  • 1,044
  • 2
  • 16
  • 35
  • 2
    Off-topic but please use [template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) rather than double or single quotes for your template strings as they [support newline characters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Multi-line_strings). – Yom T. Mar 13 '19 at 07:43
  • Do you use webpack? Imports do not work without proper setup. Have you used Vue CLI to setup the project? – Slim Mar 13 '19 at 09:22

5 Answers5

1

The error you got is as a result of not correctly importing what you want to use. There are several ways to import this library.

Import and use globally:

import Vue from 'vue'
import Vuelidate from 'vuelidate'
Vue.use(Vuelidate)

Alternatively, import a mixin directly to components:

import { validationMixin } from 'vuelidate'

var Component = Vue.extend({
  mixins: [validationMixin],
  validations: { ... }
})

Or

import { required, maxLength } from 'vuelidate/lib/validators'

Or import them individually to reduce import size:

import required from 'vuelidate/lib/validators/required'
import maxLength from 'vuelidate/lib/validators/maxLength'

You could also use require:

const { required, minLength } = require('vuelidate/lib/validators')

For your use case, validators doesn't exist in 'vuelidate/lib/validators' as it is not a property/member.

Update: From the Bootstrap example link you provided, it is possible an older version of vuelidate.

Vuelidate does not provide a default export hence this import style import validators from 'vuelidate/lib/validators' doesn't work. Using named imports on the other hand works just fine.

codejockie
  • 9,020
  • 4
  • 40
  • 46
0

You first have to add it to your app like this:

import Vue from 'vue'
import Vuelidate from 'vuelidate'
Vue.use(Vuelidate)

Then, you can use it by destructuring, like this:

import { validators } from 'vuelidate'
SrAxi
  • 19,787
  • 11
  • 46
  • 65
  • I have webpack with a app.js file and this instructions: import BootstrapVue from 'bootstrap-vue' import Vuelidate from 'vuelidate' Vue.use(BootstrapVue) Vue.use(Vuelidate) – Antonio Morales Mar 13 '19 at 07:48
0

ES6

Use named import and change the validations section as follows:

import { validators, minLength } from 'vuelidate/lib/validators';

Vue.component('newsletter', {

    template :  `<div>
      <b-form @submit="onSubmit">
        <b-form-group id="exampleInputGroup2" label="Food" label-for="exampleInput2">
          <b-form-select
            id="exampleInput2"
            :options="foods"
            :state="$v.form.food.$dirty ? !$v.name.$error : null"
            v-model="form.food"
          />
          <b-form-invalid-feedback id="input2LiveFeedback">
            This is a required field
          </b-form-invalid-feedback>
        </b-form-group>
        <b-button type="submit" variant="primary" :disabled="$v.form.$invalid">Submit</b-button>
      </b-form>
    </div>`,

    props : ['route_post'],

    data: function()
    {
        return {
            foods: ['apple', 'orange'],
            form: {}
          }
    },  

    validations: {
      form: {
        name: {
          required,
          minLength: minLength(3)
        }
      }
    },

});
vahdet
  • 6,357
  • 9
  • 51
  • 106
  • import { validators } from 'vuelidate/lib/validators'; return me this error Uncaught SyntaxError: Unexpected token { – Antonio Morales Mar 13 '19 at 07:53
  • Weird. it is a [general es6 syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Import_a_single_export_from_a_module). Is your environment ES6 compatible? – vahdet Mar 13 '19 at 08:02
  • ES5 equivalent for `import myModule from './myModule';` is sth like `var myModule = require('./myModule');`. – vahdet Mar 13 '19 at 08:09
  • Or, you make use of Babel like: https://stackoverflow.com/questions/34747693/how-do-i-get-babel-6-to-compile-to-es5-javascript – vahdet Mar 13 '19 at 08:14
0

First off, check in your node_modules if you have installed vuelidate at all:

npm install vuelidate --save

validators doesn't have exports default, you need to use destructuring to import each validation separately:

import { required, minLength } from 'vuelidate/lib/validators'; 

Vue.component('newsletter', {

... 
validations: {
name: {
  required,
  minLength: minLength(3)
},
Nikola Kirincic
  • 3,651
  • 1
  • 24
  • 28
0

Are you using vscode and vetur? Not sure if we encountered the same problem. But how I solved my problem was adding a jsconfig.json file on my root project folder and putting this code inside.

 {
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    // This is the line you want to add
    "allowSyntheticDefaultImports": true
  },
  "exclude": ["node_modules", "**/node_modules/*"]
 }

I think the import problem was due to vscode and intellisense. Does not have anything to do with vuelidate.

After you create your jsconfig and save it...restart vscode.

hayreenfly
  • 81
  • 2
  • 8