import fs from 'fs' ; import path from 'path' ; import glob from 'glob' ; import parseEsImport from 'parse-es-import' ; type ModuleExportInfo = { /** Module name */ name ; /** Path of module's source file */ moduleFilePath : string ; /** Source code of module */ rawCode : string ; } ; export type ModuleExportMap = { [ key ] : Array < ModuleExportInfo > ; } ; /**
 * Parse exported modules of file
 */ export default function parseModuleExport ( { statsModules , context , validPaths , fileDependencyMap , needRawCode , } ) { const result = { } ; if ( ! Object . keys ( fileDependencyMap ) . length ) { return result ; } for ( const { name , source } of statsModules ) { const pathCurrent = path . resolve ( context , name ) ; const dirPathCurrent = path . dirname ( pathCurrent ) ; if ( validPaths . indexOf ( pathCurrent ) === - 1 ) { continue ; } const moduleInfoList = [ ] ; const { imports , exports } = parseEsImport ( source ) ; for ( const { type , moduleName , value } of exports ) { switch ( type ) { case 'ExportSpecifier' : const [ pathImport ] = glob . sync ( path . resolve ( dirPathCurrent , `${ value }?(.jsx|.js|.ts|.tsx)` ) ) ; if ( pathImport ) { moduleInfoList . push ( { name : moduleName , rawCode : needRawCode ? fs . readFileSync ( pathImport , 'utf8' ) : '' , moduleFilePath : pathImport , } ) ; } break ; case 'FunctionDeclaration' : case 'VariableDeclaration' : let moduleFilePath = '' ; let rawCode = needRawCode ? value : '' ; for ( const { starImport , defaultImport , moduleName : importModuleName } of imports ) { if ( moduleName === starImport . replace ( /^_/ , '' ) || moduleName === defaultImport . replace ( /^_/ , '' ) ) { const [ pathImport ] = glob . sync ( path . resolve ( dirPathCurrent , `${ importModuleName }?(.jsx|.js|.ts|.tsx)` ) ) ; if ( pathImport ) { moduleFilePath = pathImport ; rawCode = needRawCode ? fs . readFileSync ( pathImport , 'utf8' ) : '' ; } break ; } } moduleInfoList . push ( { name : moduleName , rawCode , moduleFilePath , } ) ; break ; default : break ; } } result [ pathCurrent ] = moduleInfoList ; } return result ; }