How to find local resources in Tabris.js

How to find local resources in Tabris.js

The built-in, node compatible module system of Tabris.js makes it pretty easy to find and load JavaScript files within your project. NPM modules aside, all paths are relative. So even if your current module is "subProject/modules/dialogs/foo.js", you can open "subProject/modules/dialogs/bar.js" simply by calling "require("./bar");"

However, aside from .js files, your Tabris.js project may also consist of images, json, xml and/or text files that you need to access. JSON is simple, since the module system can also be used for that, e.g. "require("./bar.json");". Images (given to an "image" property, e.g. of ImageView) and text resources (which can be loaded with a local XMLHttpRequest, or – more conveniently – using the fetch module) aren’t that simple though. Both have to be addressed relative to your project root, where the package.json resides. That’s fine if you have them in a common folder:

  imageView.set("image", {src: "resources/myImage.png"});
  fetch("resources/myText.txt").then(function(result) {
    // ...
  });

But in the interest of modularization your resources may be grouped with your modules, and then the whole thing becomes cumbersome:

  imageView.set("image", {src: "subProject/modules/dialogs/myImage.png"});
  fetch("subProject/modules/dialogs/myText.txt").then(function(result) {
    // ...
  });

That may still be tolerable – until you move your modules around within your project. Let’s say you rename the "subProject" folder to "common" – suddenly you need to edit every single path that contains "subProject". There is a solution however: As of Version 1.1 Tabris.js provides the "__dirname" and "__filename" variables, same as node.js. These always point to the path of the current module, so they also follow any renames. As a result you can now simply write:

  imageView.set("image", {src: __dirname + "/myImage.png"});
  fetch(__dirname + "/myText.txt").then(function(result) {
    // ...
  });

Done!

No Comments

Sorry, the comment form is closed at this time.