Search code examples
vuejs3vue-chartjs

How to use vue-chartjs with unplugin-vue-components?


I try to use unplugin-vue-components to automatically import Vue components from vue-chartjs, but I don't know how.

I found this in unplugin-vue-components documentation:

You can also write your own resolver quickly:

Components({
  resolvers: [
    // example of importing Vant
    (componentName) => {
      // where `componentName` is always CapitalCase
      if (componentName.startsWith('Van'))
        return { name: componentName.slice(3), from: 'vant' }
    },
  ],
})

But since components from vue-chartjs don't come with a common prefix, like CBar or ChartBar, I have no idea how to config unplugin-vue-components.


Solution

  • The following will import all charts from vue-chartjs and prefix them with "C":

    import Components from 'unplugin-vue-components/vite'
    const charts = [
      'Bar',
      'Bubble',
      'Doughnut',
      'Line',
      'Pie',
      'PolarArea',
      'Radar',
      'Scatter'
    ]
    
    Components({
      resolvers: [
        (name) => {
          if (charts.includes(name)) {
            return { name: `C${name}`, from: 'vue-chartjs' }
          }
        }
      ]
    })
    
    

    CBar, CBubble, CDoughnut etc... are now available without importing them.

    Feel free to remove the charts you don't use from the names array.


    Note: you don't need a common prefix in order to auto-import components using unplugin. If you change the return line to:

       return { name, from: 'vue-chartjs' }
    

    in the above example, the charts will be auto-imported with their original names.