I have made my own npm package for react. We will call it @group/package
In that package, I made exportable hooks.
As an example, I made a hook that we will call useFetchWithRefreshToken.
In that hook, I will always call the same API_URL, but the API_URL depends of my project.
I don't want to do this on all my files that need to fetch.
const [load, loading] = useFetchWithRefreshToken({ url: API_URL + endpoint });
So, I tried to use environment variables, but as I suspected, it didn't work. The process.env values accessible from @group/package might be determined when I run npm run build / npm publish in the package, and not when I run my react app that installed it.
I can probably pass by redux to share data between my modules and my project, but I want something easier for the developer to fill in.
A .rc or .json configuration file, like babel or eslint, would be perfect.
How can I do it ?
You can define your env with prefix of REACT_APP_
. You can read more about it here: https://create-react-app.dev/docs/adding-custom-environment-variables/
ReactJS
.env
REACT_APP_API_URL=https://myurl.com
In your package you can read this env as follows
const [load, loading] = useFetchWithRefreshToken({ url: process.env.REACT_APP_API_URL + endpoint });
In case you have ejected your react app then you can find the line in webpack file where env are attached to the project and then manually add API_URL
to support your above implementation of just using API_URL
in your package.