How to configure Require.JS

4

Hello people,

I'm in doubt to set up RequireJS correctly, but I also have doubts about organizing Trees to set baseUrl and so I'll demonstrate how I'm setting up:

.
├── index.html
├── js
│   ├── boot.js
│   ├── main.js
│   ├── noConflict.js
│   └── lib
│       ├── autosize.js
│       ├── drilldownmenu.js
│       ├── easing.js
│       └── smooth-scrollbar.js
└── vendor
    ├── jquery.min.js
    └── require.js

This is the structure in the Project Tree and index.html put these settings:

<script type="text/JavaScript" data-main="js/boot" src="vendor/require.js"></script>

So far the RequireJS loads the problem is to call the jQuery , before I will show the code of the configuration boot.js :

;(function( undefined ) {
    'use strict';

    requirejs.config({
        baseUrl: "./js/lib",

        paths: {
            // Módulo jQuery
            "jquery":           "../../vendor/jquery.min",
            // [Config] jQuery
            "main":             "../main"
        },

        shim: {
            "easing":           ["jquery"],
            "smooth-scrollbar": ["jquery"],
            "drilldownmenu":    ["jquery"],
            "autosize":         ["jquery"]
        },

        map: {
            "*": {
                "jquery":       "../noConflict"
            },
            "noConflict": {
                "jquery":       "jquery"
            }
        }
    });

    // Chamando módulo principal para iniciar a aplicação
    requirejs(["main"]);

})();

When I run it works to a certain extent that is jQuery that does not load, realize that I use a technique that is noConflict and in it comes the problem, it says it does not recognize the TypeError: jQuery is undefined function and when I see in the requests the module defined in paths does not load:

IwasabletosolvetheproblemofnoConflict.jsbyusingthiscodeinthefileboot.js(FilethathastheRequireJSsettings):

;(function(undefined){'usestrict';requirejs.config({baseUrl:'js/lib',paths:{//MódulojQuery'jquery':['../../vendor/jquery.min','//code.jquery.com/jquery-3.0.0.min.js'],//Config'main':'../main'},shim:{'jquery':{exports:'$'},'easing':{deps:['jquery']},'smooth-scrollbar':{deps:['jquery']},'drilldownmenu':{deps:['jquery']},'autosize':{deps:['jquery']}},map:{'*':{'jquery':'../noConflict'},'../noConflict':{'jquery':'jquery'}}});//Chamandomóduloprincipalparainiciaraaplicaçãorequirejs(["main"]);

})();

But now autosize.js shows the following error: TypeError: $ is not a function , the code is original without any changes and I'm using version 1.18.18 on link

    
asked by anonymous 06.07.2016 / 04:56

1 answer

4

After many attempts I have been able to solve the problem and I will be passing the tutorial to help those starting to configure RequireJS:

First of all, I changed the structure of the Project:

C:.
|   index.html
|   
+---css
|   |   color.css
|   |   grid-responsive.css
|   |   style.css
|   |   support-browser.css
|   |   
|   \---font-text
|       |   web-font.css
|       |   
|       \---iconWeb
|               
+---img
|       
+---scripts
|   |   main.js
|   |   style.js
|   |   
|   +---lib
|   |       autosize.min.js
|   |       drilldownmenu.min.js
|   |       easing.min.js
|   |       nanoscroller.min.js
|   |       smooth-scrollbar.min.js
|   |       
|   \---main
|           app.js
|           base.js
|           start.js
|           
\---vendor
        jquery.min.js
        require.min.js

We will detail the Operation:

  • scripts: Folder containing JavaScripts for Events and Animations
  • scripts \ lib: Are Modifying Libraries
  • scripts \ main: JavaScript Settings
  • vendor: Third-Party Scripts

Now in index.html we should point RequireJS to \scripts\main\app.js which will be our starting point.

...
    <!-- JAVASCRIPT -->
    <script data-main="scripts/main/app" src="vendor/require.min.js"></script>
</head>

Well maybe it would be good for JavaScript before TAG </body> but I noticed that in the RequireJS settings it rewrites its code below the TAG <link> of CSS so better to agree that it does semantically.

Now we show the settings to call the whole library to be loaded asynchronously.

/* ./scripts/main/app.js */
(function (undefined) {
    'use strict';
    requirejs.config({
        baseUrl: './', // Raiz
        urlArgs: function (id, url) {
            return (url.indexOf('?') === -1 ? '?' : '&') + 'v=23';
        }, // Debug Cache
        deps: ['scripts/main/base'],
        map: {
            '*': {
                'jQuery': 'jquery'
            }
        },
        paths: {
            // Módulos
            'jquery': ['vendor/jquery.min', '//code.jquery.com/jquery-3.0.0.min'],
            // Library jQuery
            'easing': 'scripts/lib/easing.min',
            'nanoscroller': 'scripts/lib/nanoscroller.min',
            'drilldownmenu': 'scripts/lib/drilldownmenu.min',
            'autosize': 'scripts/lib/autosize.min',
            // Config
            'start': 'scripts/main/start'
        },
        shim: {
            'easing': {
                deps: ['jquery']
            },
            'nanoscroller': {
                deps: ['jquery']
            },
            'drilldownmenu': {
                deps: ['jquery']
            },
            'autosize': {
                deps: ['jquery']
            }
        },
        waitSeconds: 15
    });
    // Chamando módulo principal para iniciar a aplicação
    require(['jquery'], function ($) {
        require(['start']);
    });
    requirejs.onError = function (err) {
        console.log(err.requireType);
        console.log('modules: ' + err.requireModules);
        throw err;
    };
})();

Each item I will explain and its methods to load to libraries:

  • baseUrl: I have pointed out the root of the site or DocumentRoot of the project to RequireJS start at this point for a better visualization to avoid excessive use of ../ ;
  • urlArgs: A method with regard to cache done by browsers, which is the question of the Request, if by chance some code was delayed the browser noticed and now only need to change the v=1 to another number to update requests;
  • deps: delete the jQuery reference on the RequireJS paths;
  • map: in '*' means that all modules that define the specified module will receive the corresponding module some modules and for some reason some modules use require ("jQuery") rather than require ("jquery ");
  • paths: In this place we will assign a name for the library and its file;
  • shim: specifies library dependencies that do not bind to define() or AMD-spec compliant;
  • waitSeconds: A time to check the code, especially if you apply a loadbalancer that is being done to jQuery that will check if it is local or will fetch the official site.

Now I'm going to show a method based on the link for your global object $ :

  • Modify the RequireJS configuration to fit all modules non-AMD compatible and load all jQuery plugins at the beginning of the loading the page. (Ideal Approach)
  • Imports jQuery and all its plugins out of AMD, re-assigning the jQuery module to the global window.jQuery object.

Then look at the code:

/* ./scripts/main/base.js */
;
(function () {
    // Usando jQuery como um módulo nomeado em RequireJS
    define(['jquery'], function () {
        (function ($) {
            console.info('Verificando Global jQuery...');
            if (typeof window === 'object' && typeof window.document === 'object') {
                if (!!window && !(!!window.$)) {
                    window.jQuery = window.$ = jQuery;
                }
                console.log([$, jQuery]);
            }
            var version = $().jquery;
            if (typeof define === "function" && define.amd && define.amd.jQuery) {
                console.info('jQuery: ' + version + ' $.fn.jquery: ' + $.fn.jquery);
                return window.jQuery;
            }
        }(jQuery));
    });
}());

Now just put your settings in start.js , if you want an example to start:

/* ./scripts/main/start.js */
define(['jquery', 'easing', 'nanoscroller', 'drilldownmenu', 'autosize'], function () {
    $(document).ready(function () {
        $('.preloader').delay(350).fadeOut(function () {
            $(this).remove();
        });
        $('body').hide(0, function () {
            $('body').delay(350).show();
        }); // Force Chrome to repaint fonts
        // Init Console
        console.log(window.console);
        if (window.console || window.console.firebug) {
            console.clear();
        }
    }); // Initialize document is ready
});

See only the result of requests made by RequireJS and its order according to start.js :

    
11.07.2016 / 06:13