0

im actually not sure if this is possible , but my idea is im writing a library which will be used in another app. In my library, it depends on an external dependencies, lets call it external-A.

Example in my code

import {functionA} from 'external-A'

export function helper() {
  return functionA
}

The problem here is for some reason, i dont want to put external-A as dependencies in my library package.json ( i put it as peerDependency now), so it may not install together when user install my library, and may throw error here.

Is there anyway to write the code that when the app load this helper function, it will try to import or analyze whether the app has installed external-A or not. If no, it will return another fallback function that i define

Example of idea ( but i think its not working yet)

import {functionA} from 'external-A'

function fallBackHelper() { console.log('fallbackHelper') }

export function helper() {
  return functionA ?? fallbackHelper
}

Abit of background:

I'm using React, and my library use simple tsc to build the code. And the app assume using webpack.

Jake Lam
  • 3,254
  • 3
  • 25
  • 44
  • 1
    [JS conditional imports](https://stackoverflow.com/questions/36367532/how-can-i-conditionally-import-an-es6-module) – kelsny Sep 29 '22 at 04:31
  • @caTS thanks but following this i need to write the condition to detect whether user has install `external-A` or not so that i can import it, how to write this logic – Jake Lam Sep 29 '22 at 04:33
  • 1
    If the module couldn't be found, you'll get an error, so you would either use try-catch around it, or use `.catch` with it if you're opting for using the chainable Promise API instead. – kelsny Sep 29 '22 at 04:33

0 Answers0