0

I have been developing a library of components which I can reuse in my React projects. How can I export these components in groups of related functionality so that the corresponding import statement, of the project where my library is used, looks like the following?

import { Select1, Select2 } from 'myLib/Selects';
import { Button1, Button2 } from 'myLib/Buttons';
import { List1, List2 } from 'myLib/Lists';
CSharp
  • 1,396
  • 1
  • 18
  • 41

1 Answers1

1
// Selects.js
export {
  Select1,
  Select2
}

// Buttons.js
export {
  Button1,
  Button2
}

// Lists.js
export {
  List1,
  List2
}
kit
  • 535
  • 4
  • 10
  • When I try to import a component this way I get a module not found error: `Module not found: Error: Can't resolve 'lib.min/Buttons'`. It works if I have `import { Button1 } from 'lib.min'` however... – CSharp Sep 09 '18 at 17:17
  • @CSharp You shouldn't import from `lib.min` (which probably has bundled all the modules?) but from `myLib` as you did in the code in your question. – Bergi Sep 10 '18 at 12:23
  • @Bergi I'm trying to import from the bundled `lib.min`, that is the library I'm referring to in the original question. This currently works: `import { Button1 } from 'lib.min'` but I want to make this work: `import { Button1 } from 'lib.min/Buttons'` – CSharp Sep 11 '18 at 08:02
  • @CSharp No, that can't work. A bundled library is a single file, a single module. *Why* are you trying to import from a bundled and minified library? You should always import from the source. Your bundler will then do the appropriate rewriting of imports. – Bergi Sep 11 '18 at 08:59
  • @Bergi I found a similar question with the same problem I have. As the poster says I'm trying to replicate what `material-ui` does with imports, i.e. `import { RadioButtonGroup } from 'material-ui/RadioButton` https://stackoverflow.com/questions/44345257/import-from-subfolder-of-npm-package – CSharp Sep 11 '18 at 10:38
  • 1
    @CSharp Yes, just drop the minification and bundling before shipping the library. Provide multiple files instead, and the let the user of the library do minification and bundling themselves when they deploy their entire application. – Bergi Sep 11 '18 at 10:53
  • @Bergi if I just ship the source, as written, could I ensure the main application will be able to understand the ES6 syntax in the library? If you could point me to any resources on this, would be much appreciated, thanks! – CSharp Sep 11 '18 at 12:22
  • 1
    Yes, if (and only if) you ship the ES6 source, the bundler/transpiler used by your client will understand the ES6 export syntax. – Bergi Sep 11 '18 at 12:27