Search code examples
javascriptrequirejsjs-amd

How to use a multiple file library with requireJs


I building a project with requireJs my file structure is the following:

js/
   lib/
       noty/
           layouts/
               bottom.js
               top.js
               ...
           themes/
               default.js
           noty.jquery.js
       jquery.js
       jquery-ui.js
   user/
      user.js
   app.js

And my configuration :

    requirejs.config({
        baseUrl: 'js/lib',
        urlArgs: 'bust=' + (new Date()).getTime(),  //only for dev  : no-cache
        paths: {
            user: '../user'
        },
        shim: {
            'jquery-ui': ['jquery'],
            'jquery-tmpl': ['jquery'],
            'gridy': ['jquery']
        }
    });
    requirejs(['jquery', 'jquery-ui'],  function($){
    ....
    });

My concern is about to integrate noty which is a notification plugin that I may use in any modules. This plugin requires to load :

js/lib/noty/noty.jquery.js
js/lib/noty/layout/top.js
js/lib/noty/themes/bottom.js

I'm not sure what is the way to do that?

  • Concatenate the files ?

  • Load each file as a dependency? :

    requirejs(['jquery', 'jquery-ui', 'noty/noty.jquery.js', 'noty/layout/top.js', etc. ]

  • Creates some kind of plugin/module for requireJs?

Thanks


Solution

  • Finally I managed to implement the 3rd solution: I've created a web module that wrap the library in a file named notiy.js :

    define(['jquery',
        'noty/layouts/topCenter', 
        'noty/layouts/bottomRight',
        'noty/themes/default'], 
    function($){
    
    $.noty.defaults.timeout = 20000;
    
    return  function(type, msg){
        var topLayout = 'topCenter',
            bottomLayout = 'bottomRight',
            layout = {
                'alert'     : topLayout,
                'info'      : bottomLayout,
                'confirm'   : topLayout,
                'success'   : bottomLayout,
                'error'     : topLayout,
                'warning'   : topLayout
            };
    
        if(msg && type){
            return noty({
                text : msg, 
                layout: layout[type] || topLayout, 
                type : type
            });
        }
    }
    });
    

    I've declared the dependencies in the shim config (to fix the dependency order) in my app.js :

    requirejs.config({
    baseUrl: 'js/lib',
    urlArgs: 'bust=' + (new Date()).getTime(),  //only for dev  : no-cache
    paths: {
        user: '../user'
    },
    shim: {
        'jquery-ui'         : ['jquery'],
        'jquery-tmpl'       : ['jquery'],
        'gridy'             : ['jquery'],
        'noty/jquery.noty'  : ['jquery'],
        'notify'            : ['noty/jquery.noty']
    }
    });
    requirejs(['jquery', 'jquery-ui', 'jquery-tmpl', 'notify'],  function($, ui, tmpl, notify){
    //...
    });
    

    Ans it works like a charm!