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

NodeBB Development
  • 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?

  • 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"
    }
    ...
    


Suggested Topics


  • 0 Votes
    7 Posts
    2328 Views

  • 0 Votes
    4 Posts
    1774 Views

  • 0 Votes
    7 Posts
    2068 Views

  • 0 Votes
    3 Posts
    1891 Views

  • 0 Votes
    9 Posts
    3546 Views

| | | |