I have an API with the following interface (just for the sake of example)
export type FrogAPI = {
getFrogs(): Promise<Frog[]>
putFrogs(frogs: Frog[]): Promise<void>
}
I have 2 versions of this, 1 mock version which reads and writes from localStorage:
export class LocalStorageFrogAPI implements FrogAPI {
getFrogs(): Promise<Frog[]> {
return Promise.resolve(JSON.parse(localStorage.getItem('@frogApi/frogs')))
}
// ...
}
And a real version which works with remote apis:
export class HttpFrogAPI implements FrogAPI {
getFrogs(): Promise<Frog[]> {
return fetch('/frogs').then((res) => res.json())
}
// ...
}
For development I'm using the localStorage one, for production the http one.
Question: How do I conditional import the right one, so at build time only the right sources are included in the output js? This is important because both files became quite bulky. I also don't want to expose the localStorage version at all in production for security reasons.
If I do this:
const ApiConstructor = process.env.ENV === 'development'
? require('./LocalStorageFrogAPI')
: require('./HttpFrogAPI')
export const API = new ApiConstructor() as FrogAPI
Both sources will still be included in the generated output. What's the right way of only having the right one in the output js? Is possible with some webpack config?