laggingreflex laggingreflex - 5 months ago 11
Javascript Question

Require JS files from bower_components by saying "require('library')" possible?

I'm new to RequireJS and it seems it might not actually be possible but I'll still go ahead and ask away in case I'm missing something.

In the docs it says..


This setup assumes you keep all your JavaScript files in a "scripts" directory in your project.


  • project-directory/

    • project.html

    • scripts/

      • main.js

      • helper/

        • util.js







But what if I have to require files from my bower installed files in bower_components:



  • project-directory/

    • bower_components/

      • jquery-mousewheel

        • jquery.mousewheel.js


      • lodash

        • dist

          • lodash.js








As you see, not all libraries have the same directory hierarchy and naming convention.

So I was wondering is there a simple way to require these bower libraries without actually knowing where their main files are, maybe by simply saying

require('jquery-mousewheel');
require('loadash');


?

Answer

setup your requirejs config to use paths

requirejs.config({
    // ... config ...
    paths: {
        jquery-mousewheel: 'bower_components/jquery-mousewheel/jquery.mousewheel',
        loadash: 'bower_components/lodash/dist/lodash' 
    }
    // ... config ...
});

documentation for reference