RequireJS is a JavaScript file and module loader. To implement requireJS in our laravel project we only need few things:

1. Download the RequireJs from its official site: http://requirejs.org/docs/download.html or install it using npm

npm install requirejs

2. In our Laravel project – in head section of layout file we simply add it like any other js file

<script src="{{ asset('js/require.js')}}"></script>

after this we need to include our requirejs config file , also in head section of the document

<script src="{{asset('js/requirejs-config.js')}}"></script>

after that the requirejs is redy to use – but first we need to configure our config file
which could look like this :

requirejs.config({
    baseUrl: '/js',
    paths: {
        jquery: "jquery.min",
        weather: "custom/weather",
        bootstrap: "bootstrap/bootstrap.bundle",
        news: "custom/news",
        domReady: "plugins/domReady",
        url: "custom/url"
    },
    shim : {
        bootstrap: ["jquery"]
    }
});

this is the basic configuration for our recent project so far – the most importants are “paths” , the left side are the ids of the files and the right side are the file locations relative to base url, so example js function in our template can look like this:

 require(['jquery','weather','domReady!'], function ($, weather) {

   setInterval(function () {
      weather.updateCurrent(data.current);
   },data.current.interval);
}

and thats it , we also can use it to create new modules the only diference is to use

define(['jquery'],function($){}) 

instead of

require(['jquery'],function($){})

for more information requirejs provides documentaion: http://requirejs.org/

Leave a Reply

Your email address will not be published. Required fields are marked *

Fork us on GitHub