1

I am currently creating a React component library. This component needed a lightweight tooltip, and as I could not find anything as light as I wanted, I made another component library that I can use for the main or any other projects I want. This works very well.

However, what I'd like to do is offer users of my library a way to disable tooltips and not be penalized for doing so. From my tests it seem that, even if the tooltip is not used, it is still added to the bundle. Webpack apparently can't shake it out. It will also need to be installed as a dependency.

To give an idea of how it's used:

return (
  <div>
    {showTooltip ? (
      <Tooltip>
        //...children
      </Tooltip>
    ) : (
      //children
    )}
  </div>
);

showTooltip is just a destructured prop. I get why this doesn't work, as it's impossible for the bundler to know that showTooltip is never going to change value, but how do I do what I want here? How do I allow users to not install the tooltip lib and not be weighed down by a feature they've disabled?

Devildude4427
  • 892
  • 1
  • 8
  • 28
  • As per your use case it seems like you would have to manage external configuration file which will consists of flags like ```showTooltip``` and based on that file you would have to you Dynamic Imports https://javascript.info/modules-dynamic-imports – Dolly Sep 27 '20 at 05:12
  • Interesting. I'll definitely need to play around with this to see if it'll work. Will probably be pretty janky in a React + TS context though. – Devildude4427 Sep 27 '20 at 05:34
  • Great!, Would like to know the outcome from you, if you come up with something, Mean while we can also wait for suggestions from other SO members. – Dolly Sep 27 '20 at 05:39
  • Yeah lord only knows how I'm supposed to make that work with children needing to be passed around and strict typing. That turns into absolute spaghetti real quickly. – Devildude4427 Sep 27 '20 at 05:48
  • Finally wrangled the spaghetti into something that looks like it would work but no. TS will not allow you to do that. It cannot compile `import()` of a resource that does not exist. Not even with a `@ts-ignore`. TS spec apparently says `import()` is unconditional. So that won't work. – Devildude4427 Sep 27 '20 at 06:58
  • I beleive Dynamic Imports are supported https://stackoverflow.com/questions/18118222/dynamically-import-module-in-typescript and https://mariusschulz.com/blog/code-splitting-a-typescript-application-with-import-and-webpack – Dolly Sep 27 '20 at 10:16
  • Dynamic imports are supported, but imports where the resource might not exist are not. https://stackoverflow.com/a/59293724/8963648 Regardless, even using that syntax a bundler will include the library in the output. Doesn't work. – Devildude4427 Sep 27 '20 at 20:30

0 Answers0