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)
        }
      }
    },

});
2
  • 2
    Off-topic but please use template literals rather than double or single quotes for your template strings as they support newline characters. Commented Mar 13, 2019 at 7:43
  • Do you use webpack? Imports do not work without proper setup. Have you used Vue CLI to setup the project? Commented Mar 13, 2019 at 9:22

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Can you create a sandbox and I will have a look at it?
Please create a sandbox at codesandbox.io so I can look into what you're doing wrong. The code you have in the question is not sufficient.
It's laravel 5.7 with its stack of webpack and vuejs, it's impossible to create a sandbox that simulates it.
Create just the Vue part that you want to have Vuelidate for.
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'

1 Comment

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)
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)
        }
      }
    },

});

4 Comments

import { validators } from 'vuelidate/lib/validators'; return me this error Uncaught SyntaxError: Unexpected token {
Weird. it is a general es6 syntax. Is your environment ES6 compatible?
ES5 equivalent for import myModule from './myModule'; is sth like var myModule = require('./myModule');.
Or, you make use of Babel like: stackoverflow.com/questions/34747693/…
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)
},

7 Comments

import validators from 'vuelidate/lib/validators';//this continues return me error
@AntonioMorales, I have edited, looks like it doesn't find the 'vuelidate/lib/validators' so try with const validators = require('vuelidate/lib/validators')
@AntonioMorales in addition to my answer, I have added note at the top, since I have doubts that you have installed vuelidate?
If I use require: Uncaught ReferenceError: require is not defined
@AntonioMorales, but did you installed node module at all?
|
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.