Home » vue » Vue.js – lodash | How to import only specific functions globally?

Vue.js – lodash | How to import only specific functions globally?

Posted by: admin November 26, 2021 Leave a comment

Questions:

I currently import the whole lodash library like this:

import _ from 'lodash';
Object.defineProperty(Vue.prototype, '$_', { value: _ });

And it works fine, and I can access all the lodash functions using this.$_.startCase()

But I only use the function startCase and omit in my entire project. So I tried importing jus those functions:

import {startCase, omit} from 'lodash/core';
Object.defineProperty(Vue.prototype, '$omit', { value: omit});
Object.defineProperty(Vue.prototype, '$startCase', { value: omit});

But When I try to access these functions using this.$omit() it throws an error saying that function is not defined.

What is going wrong here?

Answers:

In order to use named imports like import {omit} from 'lodash/core', lodash/core should be ES module that has export statement for omit. lodash package is UMD, this means that it’s treated as CommonJS module by Webpack and has only default exports due to module interoperability.

lodash/core works the same way as lodash in this regard, the whole module will be imported to the bundle:

import _ from 'lodash/core';
let { omit } = _;

Functions should be either imported from separate nested lodash modules:

import omit from 'lodash/omit';

Or they should be imported from lodash-es package that provides ES modules and allows named imports:

import {omit} from 'lodash-es';