4

I am learning NativeScript. I have a basic app working. I am now trying to import a JavaScript library that I've used in the past. I'm importing the library by using:

npm install git://github.com/my-company/my-project.git --save

I've confirmed that the package is being installed. In my view model, I then add the following:

var MyLibrary = require('MyLibrary');

That line alone causes the app to crash. Basically, NativeScript cannot seem to find it (or load it). I looked, and I can see the "MyLibrary" directory in the "node_modules" directory. The directory structure looks like this:

.
node_modules
  MyLibrary
    dist
      MyLibrary.min.js
    src
      MyLibrary.js
    package.json

The MyLibrary.js file looks like this:

class MyLibrary {
    process(vals) {        
        let result = 0;
        if (vals) {
            vals.forEach(function(val) {
                result = result + val;
            });
        }
        return result;
    }
}
module.exports = MyLibrary;

The "MyLibrary.min.js" file is the result of running it through Babel and converting it to ES5. What am I doing wrong? I'm just trying to get the following code into my view model:

var MyLibrary = require('MyLibrary');
var library = new MyLibrary();
var result = library.process([1, 2, 3, 4]);
3
  • I don't know if it would help, but does require('MyLibrary/dist/MyLibrary.min.js') work? Commented Dec 29, 2015 at 8:06
  • @jasssonpet That does work. But I want to be one of the cool kids :) Commented Dec 29, 2015 at 13:03
  • Than maybe you should check the main field of the package.json. It should be pointing to the module you want require('MyLibrary') to resolve. Commented Dec 29, 2015 at 13:22

1 Answer 1

6
  1. In your package.json, add a property like this :
{
  "main": "./dist/MyLibrary.min.js"
}
  1. In your code, use your module like this :
var MyLibraryModule = require('MyLibrary');
var library = new MyLibraryModule.MyLibrary();
var result = library.process([1, 2, 3, 4]);
Sign up to request clarification or add additional context in comments.

2 Comments

I'm trying to do this for the github.com/rosiejs/rosie package. It seems like in the package.json there, it already has step 1. But requiring rosie like your method entails in step 2 still yields this error message when I do npm test ios: "Could not find module 'rosie'"
Ok for those who are using external packages installed via npm, make sure you don't do -D (save-dev), and do --save. I was able to get this to work with the js library rosie

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.