Using NPM Packages in Titanium

Lets begin with the fact that the above 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?

  1. run npm init in the app/lib directory in your Alloy project, or in your Resources directory if you use a classic app (if you still do, time to move to Alloy though)
  2. Follow the steps NPM gives you when doing the init. You don’t have to fill out anything.
  3. Run npm i [packagename] in the lib directory to install a package, lets say to.imagecache, so npm i to.imagecache
  4. Add the lib/node_modules directory and the package-lock.json file to your .gitignore folder. No need to commit all these files when they can be restored easily.
  5. On any other machine you want to set this up, just go to your lib directory, run npm install and all packages will be installed to your app.

Usage of packages

The usage is like any other module or lib file. Assuming you’ve installed to.imagecache, you can just include it like this

var imageCache = require('to.imagecache');

Because node modules are automatically found, it’ll work just as expected.

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-module keyword. When you’re creating a commonjs module/lib file that you want to share, please please publish it using the titanium-module keyword.

You can find the packages here:

As of now there is 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 titanium-module keyword!


Now comes a fun part. Dependencies! For the purpose of demonstration I’ve created a package that extends to.imagecache for the purpose of having an ImageView that caches its own image with async loading.

I’ve named this package to.cachedimageview and implementation is really simple.

  • Run npm i to.cachedimageview in your lib directory. (or Resources for classic project).
  • This will install both to.cachedimageview and to.imagecache as 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" />

Your turn

Now it is up to you. Start making awesome packages, extend the best packages out there and share them all below, on TiSlack and write blogposts about them!

Packages out there right now