Read the statement by Michael Teeuw here.
Using npm module in a module
-
@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 -
@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
- adding a package.json file to my MM module (
-
@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--save
flagnpm 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