I had a similar situation. My project structure was like this:
It was necessary for me that in production mode mocks did not get into the bundle. It was also important for me not to write conditions in every place of use and not to work with Promises.
For me the solution was to create a unifying api.js file with the code:
// solution 1
export const api = (
await import(`${process.env.NODE_ENV === 'development' ? './mockAPI.js' : './realAPI.js'}`)
).default
export default api;
With this approach in production mode, only the processed realAPI.js gets into the bundle, and the use of the solution does not require separate conditions or work with Promises, for example:
import api from './libs/api';
api.getUser();
It is also possible to use a similar solution:
// solution 2
let api = (await import('./realAPI')).default;
if (process.env.NODE_ENV === 'development') {
api = (await import('./mockAPI')).default;
}
export default api;
Both solutions allow not to include "mocks" in the bundle in production mode. This is done by removing unreachable code during the build process, important not to move the process.env.NODE_ENV === 'development' condition into a variable.
package.json
; mygulpfile
then checks if that dependency exists before performing some build steps. – Kunlunwebpack
andbabel
to transpile es6 to es5. Projects likewebpack-rewire
and similar are not to help here - github.com/jhnns/rewire-webpack/issues/12 . One way to set the test doubles OR to remove problematic dependencies could be the conditional import. – Reynoldswebpack
is used to convert stylesheets into modules that insert the relevant styles into the DOM when they're imported) but the module also needs to run outside of the browser (e.g. for unit testing). – Inedited(condition)
can be resolved at build time then different preprocessed versions of the product can be prepared and the condition removed. E.g.,(condition)
is meant to distinguish front end (browser) vs back end (common js). Then the condition statement becomes unnecessary. – Retake