How to configure Require.JS

Asked

Viewed 477 times

4

Óla gente,

I am in doubt of properly configuring the RequireJS, as I also have doubts about the organization of Trees to configure the baseUrl and so I’m going to demonstrate how I’m configuring:

.
├── 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 tree structure of the project and the index.html put these settings:

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

So far Requirejs loads the problem is to call the jQuery, before I will show the configuration code 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 spin it works up to a certain point which is the jQuery that does not carry, realize that I use a technique that is the noConflict and in it comes the problem, he says he does not recognize the function TypeError: jQuery is undefined and when I see in the requests the module defined in paths does not carry:

Requisições 200 dos arquivos sicronizados pelo RequireJS + CSS do HTML mas não carrega o jquery.min.js

I managed to solve the problem of noConflict.js using this code in the file boot.js (File you have to Requirejs settings):

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

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

        paths: {
            // Módulo jQuery
            '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'
            }
        }
    });

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

})();

But now the autosize.js shows the following error: TypeError: $ is not a function, where the code is original without changes and I am using version 1.18.18 on the website http://www.jacklmoore.com/autosize

1 answer

4


after many attempts I managed to solve the problem and I will be passing the tutorial to help those who are starting configure the 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

Let’s detail the operation:

  • scripts: Folder containing Javascripts for Events and Animations
  • lib scripts: Are Libraries of modification
  • main scripts: Javascript settings
  • vendor: Scripts de Terceiros

Now on the index.html we should point out the RequireJS to the \scripts\main\app.js that will be our starting point.

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

Well maybe it would be nice to put the JavaScript before the TAG </body> but I realized that in the settings of RequireJS he rewrites his code under the tag <link> of CSS then better agree that he does semantically.

Now let’s show the settings to call the entire library to be loaded so asynchronous.

/* ./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 pointed out the root of the site or DocumentRoot from the project to the RequireJS start at this point to put an address with the best view, to avoid excessive use of ../;
  • urlArgs: A method in relation to cache done by the browsers, which is the issue of the Request, if by chance some code was changed it would take the browser to notice and now if it is necessary to just change the v=1 to another number to update to requests;
  • deps: delete jQuery reference in 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") instead of require("jquery");
  • paths: at this location we will assign a name to library and its archive;
  • Shim: specifies the library dependencies that do not connect to define() or AMD-spec compliant;
  • waitSeconds: a time to check the code, especially if applying a loadbalancer that is being done in the jQuery who will check whether it is local or will pick up on the official website.

Now I’m going to show you a method based on https://www.caffeinecoding.com/jquery-and-amd/ in relation to its overall object $:

  • Modify the Requirejs configuration to fit all modules AMD-compatible and load all jQuery plugins at the beginning of page loading. (Ideal approach)
  • Import jQuery and all its plugins outside of AMD, then re-assign the jQuery module to the global window.jQuery object.

Then see 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 on 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 the requests made by RequireJS and its order according to the start.js: inserir a descrição da imagem aqui

  • Very good your tutorial, helped me a lot!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.