Let’s begin with the fact that the above – Using NPM Packages in Titanium – is possible. Yep, it truly is. I noticed a lot of people were unaware of the fact they could just plug in any NPM package they wanted.So… how do we set this up?
npm initin the
app/libfolder in your Alloy project, or in your
Resourcesfolder if you use a classic app (if you still do, time to move to Alloy though!).
- Follow the steps NPM gives you when doing the init. You don’t have to fill out anything
npm i [packagename]in the lib folder to install a package, let’s say to.imagecache, so
npm i to.imagecache.
- Add the
lib/node_modulesfolder and the
package-lock.jsonfile to your
.gitignorefolder. No need to commit all these files when they can be restored easily.
- On any other machine you want to set this up, just go to your
npm installand all packages will be installed to your app.
Usage of PackagesThe usage is like any other module or lib file. Assuming you’ve installed
to.imagecache, you can just include it like this:
Because node modules are automatically found, it’ll work just as expected.
var imageCache = require('to.imagecache');
How to Find the Packages?A lot of Titanium packages are found using the titanium keyword. However, to get more organised I’ve created the
titanium-modulekeyword. When you’re creating a commonjs module/lib file that you want to share, please please publish it using the
titanium-modulekeyword. You can find the packages here: https://www.npmjs.com/search?q=keywords:titanium-module As of now, there are just a couple packages, all in my name, using the keyword. However, I hope (and expect) more will be following soon. So if you’re a writer of modules, use NPM and publish it with the
DependenciesNow comes a fun part. Dependencies! For the purpose of demonstration, I’ve created a package that extends
to.imagecachefor the purpose of having an
ImageViewthat caches its own image with async loading. I’ve named this package to.cachedimageview and implementation is really simple.
npm i to.cachedimageviewin your
libfolder (or Resources for classic project).
- This will install both
to.imagecacheas the latter is dependent on the first.
- Then all you need to do is use it in an ImageView like this:
<ImageView id="myImage" module="to.cachedimageview" />