All files index.js

100% Statements 31/31
100% Branches 11/11
100% Functions 4/4
100% Lines 29/29
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 681x 1x 1x   1x 66x   1x 1x   1x 86x   6x         2x         78x         1x     87x 1x     86x   86x 78x     82x   8x 2x     6x 79x 79x   79x 1x     78x   78x     5x              
import _ from 'lodash'
import path from 'path'
import {listRequiredModules} from './utils'
 
const rootModuleName = 'material-ui'
const rootModules = _.keyBy(listRequiredModules(rootModuleName), (item) => path.basename(item))
 
const iconsModuleName = 'material-ui/svg-icons'
const iconModules = _.keyBy(listRequiredModules(iconsModuleName), _.flow(_.camelCase, _.upperFirst))
 
const createTransformerSettings = (sourceValue) => {
  switch (sourceValue) {
    case rootModuleName:
      return {
        index: rootModuleName,
        modules: rootModules,
      }
    case iconsModuleName:
      return {
        index: iconsModuleName,
        modules: iconModules
      }
    default:
      return null
  }
}
 
export default function ({types}) {
  return {
    visitor: {
      ImportDeclaration(path) {
        if (!path.node.specifiers.length) {
          return
        }
 
        const settings = createTransformerSettings(path.node.source.value)
 
        if (!settings) {
          return
        }
 
        const specifiers = path.node.specifiers.filter((spec) => types.isImportSpecifier(spec))
 
        if (specifiers.length < path.node.specifiers.length) {
          return
        }
 
        specifiers.forEach((spec) => {
          const {name} = spec.imported
          const modulePath = settings.modules[name]
 
          if (!modulePath) {
            throw new Error(`${settings.index} does not contain module "${name}"`)
          }
 
          const specifiers = [types.importDefaultSpecifier(types.identifier(spec.local.name))]
 
          path.insertBefore(types.importDeclaration(specifiers, types.stringLiteral(`${settings.index}/${modulePath}`)))
        })
 
        path.remove()
      }
    },
  }
}