import ora from 'ora' ; import { jsConfig , tsConfig } from '../templates' ; import { LANG_CONFIG , STATE_MANAGEMENT } from '../constants' ; import { Extensions , ScaffoldConfig } from '../types' ; import { createDir , writeToFile , deleteFile , replaceFileContents } from '../utils' ; const directories = [ ] ; const files = [ ] ; const flattenScaffoldConfig = ( dir , children ) => { if ( typeof children === 'string' ) { return { path : dir , isFile : true } ; } else { children && children . reverse ( ) . forEach ( ( { name , children } ) => { const { path , isFile } = flattenScaffoldConfig ( `${ dir }/${ name }` , children ) ; if ( isFile && typeof children === 'string' ) { files . push ( { path , data : children } ) ; } else { directories . push ( { path } ) ; } } ) ; return { path : dir , isFile : false } ; } } ; const enableExperimentalDecorators = async ( projectName , ts ) => { const path = `${ projectName }/${ LANG_CONFIG [ ts ? 'ts' : 'js' ] }` ; if ( ts ) { await replaceFileContents ( path , [ { subStr : /"compilerOptions": {/g , newSubStr : tsConfig ( ) , } ] ) ; } else { await writeToFile ( path , jsConfig ( ) ) ; } } ; export const writeFolderStructure = async ( projectName , scaffoldConfig , fileExtensions , isRoutingNeeded , namedExport , stateManagement ? ) => { const spinner = ora ( 'Scaffolding the folder structure...' ) . start ( ) ; spinner . start ( ) ; const { cmpExt , fileExt } = fileExtensions ; const rootPath = `${ projectName }/src` ; flattenScaffoldConfig ( rootPath , scaffoldConfig ) ; if ( isRoutingNeeded ) { const filesToBeDeleted = [ `App.${ cmpExt }` , `App.test.${ cmpExt }` , 'App.css' , 'logo.svg' ] ; await Promise . all ( filesToBeDeleted . map ( fileName => deleteFile ( `${ rootPath }/${ fileName }` ) ) ) ; } ; await Promise . all ( directories . map ( ( { path } ) => createDir ( path , true ) ) ) ; if ( stateManagement === 'MobX' ) { await enableExperimentalDecorators ( projectName , fileExt === 'ts' ) ; } if ( stateManagement === 'Redux' ) { await replaceFileContents ( `${ rootPath }/index.${ cmpExt }` , [ { subStr : /import ReactDOM from 'react-dom';/g , newSubStr : 'import ReactDOM from \'react-dom\';\nimport { Provider } from \'react-redux\';\n' , } , { subStr : /ReactDOM.render\(/g , newSubStr : `import ${ namedExport ? '{ store }' : 'store' } from './store';\n\nReactDOM.render(` , } , { subStr : /\<App \/\>/g , newSubStr : `<Provider store={store}>
      <App />
    </Provider>` , } ] ) ; } if ( isRoutingNeeded ) { await replaceFileContents ( `${ rootPath }/index.${ cmpExt }` , [ { subStr : /import App from '.\/App';/g , newSubStr : `import ${ namedExport ? '{ Router }' : 'Router' } from './router';` , } , { subStr : /\<App \/\>/g , newSubStr : '<Router />' , } ] ) ; } await Promise . all ( files . map ( ( { path , data } ) => writeToFile ( path , data ) ) ) ; spinner . succeed ( 'Folder structure successfully scaffolded!' ) ; } ;