Nuxt plugin imports abuse vendors

Viewed 226

I am trying to use vuejs-datepicker in a nuxt app, everything is done by nuxt plugin usage standarts.

plugins/vue-datepicker.js

import Vue from 'vue'
import Datepicker from 'vuejs-datepicker'

Vue.component('Datepicker', Datepicker)

nuxt.config.js

plugins: [
  { src: '~/plugins/vue-datepicker', ssr: false }
],

But even when it is not used I am getting its dist uploaded in the vendors/app....js after the build. How can make nuxt create a separate chunk for it and import that chunk only in the pages which are using it?

enter image description here

3 Answers

So yeah, there is basically a feature request open for this kind of use-case.

But looking at the Nuxt lifecycle, it looks like the plugins are imported even before the VueJS instance is done. So, you cannot lazy load it if it's done ahead of Vue.

But, you can totally import vuejs-datepicker on the page itself, rather than on the whole project. This may be enough

import Datepicker from 'vuejs-datepicker' // then simply use `Datepicker` in the code below

If it's not, you can maybe try this solution: https://github.com/nuxt/nuxt.js/issues/2727#issuecomment-362213022

// plugins/my-plugin
import Vue from 'vue'
export default () => {
  // ...
  Vue.use(....)
}

// adminLayouts
import myPlugin from '~/plugins/my-plugin'
export default {
  created() {
    myPlugin()
  }
}

So, the downside is that you have to import the component each time that you need it rather than having it globally but it also allows you to load it only on the concerned pages too and have it chunked per page/component.

If you were trying to find a way to split the component from vendor but you were getting a document is not defined error you can use this syntax to import your component, it will create a separate chunk with your component and use it only in client-side.

components: {
  Datepicker: () => import('vue-datepicker')
}

Also, it would be helpful to wrap your component in <client-only> tag for most of the cases.

The plugin I was trying to import used window. For this reason, any other suggested workaround still caused nuxt to crash or error in my case. I searched the whole wide web and the solution below is the only one that allows my app to run.

Instead of importing the plugin with an ES6 import, you can import it in your mounted hook, which should run in the client only. So:

async mounted() {
  const Datepicker = await import('vuejs-datepicker');
  Vue.use(Datepicker);
}

I do not know about the specific plugin you are trying to use, but in my case I had to call Vue.use() on the default property of the plugin, resulting in Vue.use(MyPlugin.default).

Related