Sapnesh Naik
Sapnesh Naik

Reputation: 11656

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

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?

Upvotes: 0

Views: 1016

Answers (1)

Estus Flask
Estus Flask

Reputation: 223094

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';

Upvotes: 2

Related Questions