Including an external javascript library in pebble js file?

后端 未结 3 1835
孤街浪徒
孤街浪徒 2021-01-21 08:41

Is there any way I can include an external JS library in my pebble code? Conventionally on a webpage I would do this in my head tags:



        
3条回答
  •  心在旅途
    2021-01-21 09:00

    I am not sure if there have been changes since the above answer, but it looks like there is in fact a way to include additional resources while keeping things tidy. On the pebbleJS page, there is the following section with an some information on the subject.


    GLOBAL NAMESPACE - require(path)

    Loads another JavaScript file allowing you to write a multi-file project. Package loading loosely follows the CommonJS format. path is the path to the dependency.


    You can then use the following code to "require" a JS library in your pebble project. This should be usable on both Cloud Pebble as well as native development.

    // src/js/dependency.js
    var dep = require('dependency');
    

    You can then use this as shown below:

    dep.myFunction(); // run a function from the dependency
    dep.myVar = 2; // access or change variables
    

    Update: After some digging into this for my own, I have successfully gotten CloudPebble to work with this functionality. It is a bit convoluted, but follows the ECMAScript 6 standards. Below I am posting a simple example of getting things set up. Additionally, I would suggest looking at this code from PebbleJS for a better reference of a complex setup.

    myApp.js

    var resource = require('myExtraFile');        // require additional library
    
    console.log(resource.value);                  // logs 42
    
    resource.functionA();                         // logs "This is working now"
    

    myExtraFile.js

    var myExtraFile = {                           // create a JSON object to export
    
      "value" : 42,                               // variable
    
      functionA : function() {                    // function
        console.log("This is working now!");
      }
    };
    
    this.exports = myExtraFile;                   // export this function for
                                                  // later use
    

提交回复
热议问题