Home > Enterprise >  Is there a better way I can import/export a library of components?
Is there a better way I can import/export a library of components?

Time:09-30

I have a component library where I use index.ts to import/export the components. As I build components, I have to add more imports along with more exports. The work grows by O(n).

Is there a way I can export all imported files? That way I would only have to do import the components, which would cut the work in half. These components will be named imports such as import { ComponentOne, ComponentTwo } from '@library'

index.ts

// Imports: Components
import ComponentOne from '../src/components/ComponentOne';
import ComponentTwo from '../src/components/ComponentTwo';
import ComponentThree from '../src/components/ComponentThree';
import ComponentFour from '../src/components/ComponentFour';

// Exports
export {
  ComponentOne,
  ComponentTwo,
  ComponentThree,
  ComponentFour,
}

CodePudding user response:

You can use babel-plugin-module-resolver which can simplify the require/import paths in your project. For example, instead of using complex relative paths like ../../../../utils/my-utils, you can write utils/my-utils. It will allow you to work faster since you won't need to calculate how many levels of the directory you have to go up before accessing the file.

// Use this:
import MyUtilFn from 'utils/MyUtilFn';
// Instead of that:
import MyUtilFn from '../../../../utils/MyUtilFn';

// And it also work with require calls
// Use this:
const MyUtilFn = require('utils/MyUtilFn');
// Instead of that:
const MyUtilFn = require('../../../../utils/MyUtilFn');

CodePudding user response:

You could also look at Re-exporting/Aggregating per MDN Docs

Syntax would be cleaner i.e:

export { ComponentOne } from '../src/components/ComponentOne';
  • Related