MagicMirror² v2.12.0 is available! For more information about this release, check out this topic.

Using npm module in a module



  • Hi,

    I just started with MagicMirror, and now I want to write my own MM module.
    Is there any documentation on how to use an npm module in an MM module?

    Thanks,

    Pascal



  • @prapicault the nodejs npm modules are used by the require() clause

    var xxxx = require(‘nom_module_name’)

    then see the services (methods) provided there…
    see my sample module here

    https://github.com/sdetweil/SampleModule


  • Module Developer

    @prapicault In addition to that, the require method is used in node_helper.js files. As far as I know the require function does not work in the main module .js file. You need to reference the (main) script of the node module via the function getscripts there.

    All scripts included are of course installed via console: npm install NODE_MODULE

    An example of using them in both environments:

    node_helper.js file

    var NodeHelper = require('node_helper');
    var request = require('request');
    

    very easy, you can now use request as a function.

    A bit different with the main MMM-module.js file:

      // Define required scripts. Chart.js needed for the graph.
      getScripts: function() {
        return [
          'modules/MMM-Buienalarm/node_modules/chart.js/dist/Chart.bundle.js',
        ];
      },
    

    Basically, the script is appended to the one you’re writing. Now you can use the functions integrated in the referenced script.



  • Thanks you both. I’ve managed to get going by:

    • adding a package.json file to my MM module (npm init --yes)
    • add my dependencies to this new file, then npm install
    • add a getScripts entry in my main js file, referencing the various dependencies included in my module

  • Module Developer

    @prapicault said in Using npm module in a module:

    add my dependencies to this new file, then npm install

    Great!
    Instead of manually adding dependencies to package.json you can as well install the module with a --saveflag

    npm install axios --save
    

    Automatically adds it as dependency to package.json.

    npm uninstall axios --save
    

    automatically removes it from package.json.



  • be careful loading lots of services in the modulename.js via getscripts… all that is loaded into the browser… (and every instance of the browser used)

    load them in the node_helper via require as single instance, and move the memory and load to the server side


Log in to reply