How import an utility method (in another file) in client script.


  • GNU/Linux

    I need to create a file utility.js with some utility methods and I must use this utility methods in some client scripts.
    Suppose to have in a lib(folder) a file utility.js that does this:

    'use strict';
    
    var Utils = {};
    
    Utils.getPrint = function() {
        return "hello";
    };
    
    module.exports = Utils;
    
    

    I want use this method in some client scripts but I don't know what I have to do this. I think something like this ( but it doesn't work) :

    'use strict';
    
    (function() {
    // I must import utils.js file but I don't know how do this. Something like 
    var utils=require();
        $(document).ready(function() {
    
    
            });
    
    
    }());
    

    I want avoid to rewrite the same method in every client file it's not the correct solution. Anyone can help me?


  • Admin

    I'd create a require.js module and define it in the modules section of your plugin.json👍

    define('myplugin/utils', [], function () {
        var Module = {};
    
        Module.foo = function () { return 'bar'; }
    
        return Module;
    });
    

    Somewhere else...

    require(['myplugin/utils'], function (utils) {
        console.log(utils.foo());    // 'bar'
    });
    

    and in plugin.json:

    ...
    "modules": {
        "myplugin/utils.js": "relative/path/to/your/utils.js"
    }
    ...
    

Log in to reply
 


Star

Looks like your connection to NodeBB was lost, please wait while we try to reconnect.