简体   繁体   中英

Importing from validator in javascript

I want to use the validator for an express project. How do I import just two subsets of the packages directly?

Like:

import {isEmail, isEmpty} from 'validator';

or importing each on a separate line.

I just want to know if there is another option apart from import validator from 'validator'; as stated on the https://www.npmjs.com/package/validator

const isEmailValidator = require('validator').isEmail;
const isEmptyValidator = require('validator').isEmpty;


isEmailValidator('bla@bla.com');

Like this you mean? What you wrote should also be valid:

import {isEmail, isEmpty} from 'validator';

isEmail('bla@bla.com');

Edit for clarification: As you can see here https://github.com/chriso/validator.js/blob/master/src/index.js the library is exporting an object with each function. You can import everything import validator from 'validator' or you can use destructuring to get only a few properties.

const {isEmail, isEmpty} = require('validator');

This will not actually stop node from importing all of validator though. This just has node load the validator object that is returned from that modules export and then destructures isEmail and isEmpty out of the exported Object.

Maybe whenever ES6 modules become full supported you can use the regular import syntax. See node.js documentation: ECMAScript Modules .

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