Can I use IsDebugMode
to switch out import libraries?
Can I do:
if (IsDebugMode) {
import { SQLiteMock, SQLiteObject } from '../mocks/SQLiteMock';
}
else {
import { SQLite, SQLiteDatabaseConfig, SQLiteObject } from '@ionic-native/sqlite';
}
No, unfortunately you can't conditionally import libraries. What you can do though is import both libraries, inject both in your constructor and then conditionally using
isDevMode()
, (there exists no isDebugMode()) you can use whatever you prefer for each case.This is not a very good solution though, as it means you will load both libs in memory and since you inject them in the constructor the treeshaking that happens at build time will not ommit them.
If this is done sparingly it might even not make a difference though (negatively). I suggest you benchmark Memory size at runtime using dev tools and if there is significant gain to outweigh the manual nature of the cleaner approach, then just replace the Mock class in the import when you are done developing the feature using that Mock.
Even though some plugins may work when running the app on the browser (when using
ionic serve
), I like to inject a mock version of the plugin, to avoid warnings in the console (or errors being thrown because of cordova.js not being found).The easiest way I found to do this is by using factories, to decide which implementation of the plugin should be injected. I'll show you a demo using the
Keyboard
cordova plugin just to keep this short, but the same can be done with any cordova plugin (even if it's not part of Ionic Native).In my
providers
folder, I have a custom folder namedplugins
and inside of that folder I've added a file with the namekeyboard.provider.ts
. Inside of that file, I've defined the following:Like you can see there, I'm just creating two classes that extend the
Keyboard
class, and in the browser implementation I just write a few things in the console, and return a mocked response. You can do whatever you want inside of those methods.To know what methods you should mock, you can inspect the
index.d.ts
file of that plugin.The mobile implementation does not define anything, so the method from the super class (the Keyboard plugin) will be used.
The most important part of the code is the last past:
The
keyboardFactory
gets an instance of thePlatform
and we use that instance to check if te app is being executed in the browser, or in a cordova device. Based on that, we return the browser implementation, or the mobile one.The
keyboardProvider
just tells angular that it should use thekeyboardFactory
factory to create instances of theKeyboard
class, and that the factory depends on an instance of thePlatform
to work properly.Now the only thing left to be done, is to tell the main module (the one in the
app.module.ts
file) to use our custom provider.