How import utility method in client script

NodeBB Plugins
  • I create a new utils.js file in lib, and in this file I use this code:

    
    var Utils = {};
    
    
    Utils.getTipoBookmarked = function(oggettoBookmarked, tipoBookmarked) {
    	
    	...
    };
    Utils.checkIsChecked = function(selezionatiBookmarked, bookmarked) {
    	....
    };
    
    module.exports = Utils;
    

    Now I need to use these methods in a static/lib/add.js. (client file). This client file is something like this:

    'use strict';
    
    
    (function() {
    
    	$(document).on('click', '#buttonV', function() {
    //here I use the method in utils.js
    //The parameter is not a problem The problem is that utils is not defined
    var d=utils.getTipoBookmarked(param1,params2);
    });
    }());
    

    My problem is that the utils.js is not define. How I can import this?Anyone can help me?

  • Assuming they are utility functions and not calling any server modules, you can wrap it in an IIFE and include it in your scripts in plugin.json. Checking the environment before exporting.

    (function () {
      var Utils = {};
    
      Utils.getTipoBookmarked = function(oggettoBookmarked, tipoBookmarked) {
    	
    	...
      };
      Utils.checkIsChecked = function(selezionatiBookmarked, bookmarked) {
    	....
      };
    
      if (typeof module === 'object' && module.exports) {
        module.exports = Utils;
      } else {
        window.myutils = Utils; // Edited
      }
    }());
    
  • @yariplus said in How import utility method in client script:

    window.utils = Utils;

    Watch out for this, it would overwrite the utils object from nodebb.

  • @baris Ah, nice.

    @Doppy Best to name it something like myutils, or prefixed with the name of your plugin.


Suggested Topics