Search code examples
javascriptvuejs3viterollupjs

function name not available in production build in vite global import


I'm using vite global import feature to register some functions in globalProperties in vue 3 app to achive global $filters array in main.ts.

It works propely in development time but after production build func.name always is empty string and dose not contain function name.

Object.values(import.meta.glob<Function[]>('./common/filters/*.filter.ts', 
{ eager: true, import: 'default' }))
  .forEach(filters => filters.forEach(func => app.config.globalProperties.$filters[func.name] = func))

app.mount('#app')

currency.filter.ts

const filters: Function[] = [
  function currency(value: string) {
    if (!value)
      return value

    return `${value.toLocaleString()}$`
  },
]
export default filters

and finally I can use them inside vue components like filters in vue 2:

{{ $filters.currency(item.price) }}

how can solve this issue or is there better way to import all functions inside files in a directory and register in globalProperties

console log of app.config.globalProperties.$filters in dev:

{
   currency: ƒ currency(value)
   length:1
   name:"currency"
}

Solution

  • I managed to solve this issue by changing the way that I defined my filter functions from an array of functions to an object of functions. by defining functions inside an array after transpile to ES5 it removes the function name and call by array index and it issues the problem

    import moment from 'moment'
    const formattedDate = function (value: string, format = 'DD, MMM-YYYY, HH:mm') {
      if (value === null)
        return value
      moment.locale('en')
      return moment.utc(value).local().format(format)
    }
    const shortDate = function (value: string) {
      moment.locale('en')
      return moment.utc(value).local().format('DD,MMM,YYYY')
    }
    const friendlyTime = function (value: string) {
      if (value === null)
        return value
      return moment(value).local().fromNow()
    }
    
    export default { formattedDate, shortDate, friendlyTime }