All files index.js

100% Statements 37/37
90% Branches 9/10
100% Functions 7/7
100% Lines 33/33
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 68 69 70 71 72 73 74 75 761x 2x 2x 2x     8x 16x     8x 8x         8x     8x       8x 5x 5x 5x       5x         3x 3x       8x 8x   5x 5x 5x 5x       8x 8x 8x   8x 8x   8x             2x       16x 8x 8x          
module.exports = function ({ types: t, template }) {
  const visited = Symbol('visited')
  const importCssId = Symbol('importCssId')
  const loadTemplate = template(
    'Promise.all([IMPORT, IMPORT_CSS(MODULE)]).then(proms => proms[0])'
  )
  const getImportArgPath = p => p.parentPath.get('arguments')[0]
  const trimChunkName = baseDir => baseDir.replace(/^[./]+|(\.js$)/g, '')
 
  function getImportCss(p) {
    Eif (!p.hub.file[importCssId]) {
      const importCss = p.hub.file.addImport(
        'babel-plugin-dual-import/importCss.js',
        'default',
        'importCss'
      )
      p.hub.file[importCssId] = importCss
    }
 
    return p.hub.file[importCssId]
  }
 
  function createTrimmedChunkName(importArgNode) {
    if (importArgNode.quasis) {
      const quasis = importArgNode.quasis.slice(0)
      const baseDir = trimChunkName(quasis[0].value.cooked)
      quasis[0] = Object.assign({}, quasis[0], {
        value: { raw: baseDir, cooked: baseDir }
      })
 
      return Object.assign({}, importArgNode, {
        quasis
      })
    }
 
    const moduleName = trimChunkName(importArgNode.value)
    return t.stringLiteral(moduleName)
  }
 
  function getMagicCommentChunkName(importArgNode) {
    const { quasis, expressions } = importArgNode
    if (!quasis) return trimChunkName(importArgNode.value)
 
    const baseDir = quasis[0].value.cooked
    const hasExpressions = expressions.length > 0
    const chunkName = baseDir + (hasExpressions ? '[request]' : '')
    return trimChunkName(chunkName)
  }
 
  function promiseAll(p) {
    const argPath = getImportArgPath(p)
    const importArgNode = argPath.node
    const chunkName = getMagicCommentChunkName(importArgNode)
 
    delete argPath.node.leadingComments
    argPath.addComment('leading', ` webpackChunkName: '${chunkName}' `)
 
    return loadTemplate({
      IMPORT: argPath.parent,
      IMPORT_CSS: getImportCss(p),
      MODULE: createTrimmedChunkName(importArgNode)
    }).expression
  }
 
  return {
    name: 'dual-import',
    visitor: {
      Import(p) {
        if (p[visited]) return
        p[visited] = true
        p.parentPath.replaceWith(promiseAll(p))
      }
    }
  }
}