Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Using Gruntfile.js? Reply To: Using Gruntfile.js?

#168658
jamygolden
Member

First to get requirejs working:

Link to require script in HTML:
<script data-main="js/config" src="js/vendor/require.js"></script>
js/config points to the js/config.js file and the src points to the requirejs lib.

config.js:

    require.config({
        baseUrl: 'js',
        deps: ['main'],
        shim: {
            // Assuming you have global plugins
            'vendor/jquery': {
                exports: '$'
            }
        }
    });

main.js

    require([
        'example'
    ],
        function (example) {
            example.init();
    });

example.js

    define(function () {

    var example = {
        init: function() {
            alert('Example ran');
        }
    };

    return example;
});

Your require scripts should be working within the browser

As for Grunt:

Assuming you have a project set up as follows:

    - GruntFile.js
    - package.json
    - js
        - config.js
        - main.js
        - vendor
            - almond.js
            - jquery.js

https://github.com/jrburke/almond
You can pretend that almond is part of requirejs. It allows for require to compile to a js file that is completely independant of require (how I imagine most people think it should be anyway).

The requirejs npm grunt package should be added to grunt correctly. https://www.npmjs.org/package/grunt-contrib-requirejs

In case anyone is confused about as to how it’s done, check out https://css-tricks.com/grunt-people-think-things-like-grunt-weird-hard/
Add the following to the to the devDependencies object in the package.json file:
"grunt-contrib-requirejs": "^0.4.3",

requirejs: {
    compile: {
        options: {
            baseUrl: 'js', // relative to GruntFile.js
            name: 'vendor/almond', // relative to baseUrl
            deps: ['main'], // relative to baseUrl
            mainConfigFile: 'js/config.js', // relative to GruntFile.js
            optimize: 'uglify',
            out: 'js/site.js' // relative to GruntFile.js
        }
    }
}

Running grunt should create a js/site.js file. You now point you script to that file for production use.

I’ll create a quick github repo with a working example of all of this. Let me know if anything is confusing.