all files / src/ index.js

16.13% Statements 5/31
0% Branches 0/16
0% Functions 0/4
16.67% Lines 5/30
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                                                                                                                                          
const { existsSync } = require('fs')
const { join, resolve, isAbsolute } = require('path')
 
module.exports = ({ types }) => {
  return {
    visitor: {
      ImportDeclaration(path, { opts }) {
 
        const { node } = path
        let { value } = node.source
 
        node.source = Object.assign(node.source, replaceDependence(value, opts))
      },
      CallExpression(path, { opts }) {
 
        const { node } = path
        const { name } = node.callee
 
        if (types.isIdentifier(node.callee)
            && name === 'require'
        ) {
          const [{value: v}] = node.arguments
 
          if(v && typeof v === 'string'){
            node.arguments[0] = Object.assign(node.arguments[0], replaceDependence(v, opts))
          }
        }
      }
    }
  }
}
 
function getNodeValue(depName){
    return {
      value: depName,
      extra: {
        rawValue: depName,
        raw: JSON.stringify(depName)
      }
    }
  }
 
  function replaceDependence(depName, {
    platform,
    extensions = ['.js', '.json', '.vue'],
    path = 'dist'
  }) {
    let root = process.cwd()
    let result = getNodeValue(depName)
    let prefixPath = ''
 
    if (!platform) return result
 
    prefixPath = isAbsolute(path)
      ? join(path, platform)
      : join(root, 'node_modules', depName, path, platform)
 
    // if the appended path exists, replace the origin path with it
    if (Array.isArray(extensions)) {
 
      let ext, fullPath
 
      for (let i in extensions) {
        ext = extensions[i]
        fullPath = join(prefixPath, `index${ext}`)
        console.log(fullPath)
        if (existsSync(fullPath)) {
          return getNodeValue(join(depName, platform))
        }
      }
    }
    return result
  }