0
votes

I'm trying to use lodash with Nuxt2 Composition API (https://composition-api.nuxtjs.org/)

However, with useContext() I'm not able to find any global Vue prototype functions. So when I tried it by creating a module with nuxt modules. And I got the $lodash in useContext(). But when I call $lodash.all([true, false]) it says $lodash.all is not a function.

The only trick it made the $lodash available in nuxt context was using inject. I'm sharing my setup.

// modules/lodash/index.js

const path = require('path')

module.exports = function nuxtLodash(moduleOptions) {
  const lodashOptions = Object.assign({}, this.options.lodash, moduleOptions)

  // Register plugin
  this.addPlugin({
    src: path.resolve(__dirname, 'plugin.js'),
    ssr: false,
    fileName: 'lodash.js',
    options: {
      lodashOptions
    }
  })
}
// modules/lodash/plugin.js
import Vue from 'vue'
import VueLodash from 'vue-lodash'
import lodash from 'lodash'

Vue.use(VueLodash, { name: '$_', lodash })

export default function(ctx, inject) {
  inject('lodash', lodash)
}

// nuxt.config.js
  modules: [
    // ... other modules
    '~/modules/lodash'
  ],

Now, when I'm using this in my components with composition api, I'm getting an error.

<script>
import {
  defineComponent,
  useContext
} from '@nuxtjs/composition-api'

export default defineComponent({
  setup() {
    const { $lodash } = useContext()
    console.log($lodash)
    console.log($lodash().all([true, false]))
  }
})
</script>

Any proper way to use this? What am I missing here?

2

2 Answers

0
votes

The easiest idea would be importing functions you need via import { all } from 'lodash-es (and installing lodash-es as dependency). This way, you don't add the whole lodash library to your bundle and don't have any issues with imports.

import {
  defineComponent
} from '@nuxtjs/composition-api'

import { all } from 'lodash-es'

export default defineComponent({
  setup() {
    console.log(all([true, false]))
  }
})
0
votes

Finally, after a bunch of issues in the libraries and platforms it self I was able to solve it. There were multiple things which was causing issues.

  1. Node 14 module issue: https://github.com/lodash/lodash/issues/4800
  2. Must use import to load ES Module: https://github.com/lodash/lodash/issues/5033
  3. Some ESM issue: https://github.com/standard-things/esm/issues/855

And after bunch of other issues, loaded lodash with babel:

https://www.npmjs.com/package/babel-plugin-lodash

Added normal lodash and dev babel-plugin-lodash dependencies.

As nuxt has babel support inbuilt, added a plugin in the babel list:

 build: {
    babel: {
      plugins: ['lodash']
    }
  }

And then it seems like a normal _ import works!