Saturday, 28 May 2022

How to recursively export all from folders in node js project?

In my React JS project I have configured a jsconfig.json such that I can recursively export nested directories and import a specific export from the base directory as follows:

jsconfig.json:

{
  "compilerOptions": {
    "jsx": "react",
    "baseUrl": "src"
  }
}

Project folder structure:

react-app
  src
    common
    index.js
      services
        ServiceA.js
        ServiceB.js
        index.js
      components
        ComponentA.jsx
        index.js
    pages
      pageA
        PageA.jsx
        index.js
    App.jsx
    index.js
    

Now in each index.js I would export all from each file/folder. So for example in common/services/index.js:

export * from 'common/services/ServiceA.js';
export * from 'common/services/ServiceB.js';

And in common/index.js:

export * from 'common/services';
export * from 'common/components';

Now if I require ServiceA exported from ServiceA.js in the PageA.jsx file I could import it as follows:

// PageA.jsx
import {
  ServiceA
} from 'common';
// ServiceA.js
export class ServiceA {
  doStuff () {
    // do stuff
  }
}

How can I setup my NodeJS server project to allow for similar exports and imports?

I'd like to do this for consistency between the FE and BE such that I can easily port over any FE code to my BE project without having to make any significant changes to exports and imports.



from How to recursively export all from folders in node js project?

No comments:

Post a Comment