Rashid
Rashid

Reputation: 1740

Combine multiple "import * as <name> from '<path>' which contains multiple export const into 1 export for index.js

Suppose I have 2 files let say filters.js and utils.js. Both contains multiple export const like below:

utils.js

export const formatDate = (
  value,
  formatting = { month: 'short', day: 'numeric', year: 'numeric' }
) => {
  if (!value) return value
  return new Intl.DateTimeFormat('en-US', formatting).format(new Date(value))
}

/**
 * Return short human friendly month representation of date
 * Can also convert date to only time if date is of today (Better UX)
 * @param {String} value date to format
 * @param {Boolean} toTimeForCurrentDay Shall convert to time if day is today/current
 */
export const formatDateToMonthShort = (value, toTimeForCurrentDay = true) => {
  const date = new Date(value)
  let formatting = { month: 'short', day: 'numeric' }

  if (toTimeForCurrentDay && isToday(date)) {
    formatting = { hour: 'numeric', minute: 'numeric' }
  }

  return new Intl.DateTimeFormat('en-US', formatting).format(new Date(value))
}

// Strip all the tags from markup and return plain text
export const filterTags = (value) => value.replace(/<\/?[^>]+(>|$)/g, '')

filters.js

export const title = (value, replacer = ' ') => {
  if (!value) return ''
  const str = value.toString()

  const arr = str.split(replacer)
  const capitalizedArray = []
  arr.forEach((word) => {
    const capitalized = word.charAt(0).toUpperCase() + word.slice(1)
    capitalizedArray.push(capitalized)
  })
  return capitalizedArray.join(' ')
}

export const avatarText = (value) => {
  if (!value) return ''
  const nameArray = value.split(' ')
  return nameArray.map((word) => word.charAt(0).toUpperCase()).join('')
}

Now, in my index.js, I want to combine the 2 and export it again. Here's my not working code

import * as Filters from './filters'
import * as Utils from './utils'

export { Filters, Utils }

This compiles okay and I can use import {avatarText } from '@utils' where I just alias the @utils for their path.

The import avatarText wont work and doing a debug, it shows this result

enter image description here

each of the Module their contains the array of the method I put as export const.

What shall I do to fix this?

Upvotes: 1

Views: 59

Answers (1)

DDomen
DDomen

Reputation: 1878

Have you already tried:

// index.js
export * from './filters'
export * from './utils'

Note that in this case you must not have name collisions.

Upvotes: 2

Related Questions