Md Adil Md Adil - 2 months ago 16
Node.js Question

Load modules from lodash on demand

I am using Browserify with Babel and Gulp.
Currently my project requires very few part of

lodash
and i don't want to load whole modules.

import assignIn from 'lodash/assignin';
import isPlainObject from 'lodash/isplainobject';
import isFunction from 'lodash/isfunction';


Above code is working fine but a bit time consuming that i have to specify whole path repeatedly.
wouldn't it be good if it could be done as:

import {assignIn, isPlainObject, isFunction} as _ from 'loadash';


and use it as
_.assignIn
. and i can get namespace as
_
too.
Am I doing something wrong there is another way of doing or this is the only way.

Answer

If you can use the babel-plugin-lodash plugin, it does pretty much what you want.

Instead of:

import assignIn from 'lodash/assignin';
import isPlainObject from 'lodash/isplainobject';
import isFunction from 'lodash/isfunction';

you can just use:

import _ from 'lodash';

and the output from the browserify will be transformed.

For example:

import _ from 'lodash';

function Foo() {
  this.a = 1;
}

Foo.prototype.b = 2;

_.assignIn({ 'a': 0 }, new Foo);

_.isPlainObject({});

_.isFunction(/abc/);

without the plugin:

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
...

with the plugin:

var _isFunction2 = require('lodash/isFunction');

var _isFunction3 = _interopRequireDefault(_isFunction2);

var _isPlainObject2 = require('lodash/isPlainObject');

var _isPlainObject3 = _interopRequireDefault(_isPlainObject2);

var _assignIn2 = require('lodash/assignIn');

var _assignIn3 = _interopRequireDefault(_assignIn2);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
...