I am developing typescript package that should be used simple as "npm install " for Node.js, React and RN.
Most of functionality of the package works in bare js without any problem, but also there is special files that should be used for react only or for RN only.
For example, if package is installed in React project, then user can import special hooks from /react folder.
Code separating is done in two ways: either using dynamic imports, either forcing the user to import part of the package himself (like with hooks, they are just here, not used if not imported by user)
Dynamic import usage example:
private async _setupRN(config: PackageConfig) { const { subscribeForAppStateChanges } = await import("./rn"); ... ); }; if (config?.enableReactNative) { this._setupRN(config); }
So, the problem:If I just use the package by copying folder to ts-node / ts react / ts RN projects then everything works fine. (Even when using platform-specific functionality)
If I publish package to npm as it is (.ts files) and install it, then it works fine only in React Native. React, for example, throws errors on type definitions or import / export statements.
If I go all-in, and try to tsc --build package before uploading to npm (.js files) and install it, then it works fine in Node.js and React Native. But React project gives me this error:
Module not found: Error: Can't resolve 'react-native' in '.../node_modules/@appklaar/appklaar_sdk/rn'
And now, the most interesting:Even If I completely remove import of files that uses react-native, so code that imports from 'react-native' should never be executed, I still get the same error. Looks like react is trying to require even unused files.
Why does it happen? How to fix it? react and react-native are my package's peer dependencies. I have a guess that probably I am making tsx --build wrong way (it wont build if RN is just peer dependency, so i added it as devDependency also). But if thats the problem, then why in Node.js project everything works fine?
I am ok with making tsc --build every time when I want to update the package. I just want this to work everywhere.
I do not want to split package into 3 packages for each platform. I am completely sure that I am close to solution.
Package link if you want to check the code:https://www.npmjs.com/package/@appklaar/appklaar_sdkRN functionality is inside "rn" folder. Dynamic import is used in Connector file.Version 1.4.12 was uploaded as .js files, version 1.4.13 was uploaded as .ts files.