EsTeGe
EsTeGe

Reputation: 3065

jQuery not working with RequireJS when in subfolder

I have the following folder structure:

In index.html I added the following line to the head section:

<script data-main="js/main" src="js/libs/require.js"></script>

When I add a simple alert to main.js, it works. When I want to use jQuery, it's not working:

require(['libs/jquery'], function ($) {
    $('#test').html('123');
});

In the chrome web inspector, I see that jquery loaded succesfully, but the text doesn't appear in my div. When I move jquery out of ./js/libs and just put it in ./js (and ofcourse change the dependency to ['jquery']), it works.

What am I doing wrong? Why can't I just put jquery in ./js/libs to keep things organized?

Thanks

Upvotes: 4

Views: 3009

Answers (2)

Yaplex
Yaplex

Reputation: 2284

You have to provide basePath in order it to work correctly. In your case it's just js. You can do it in the beginning on main.js file.

require.config({
    baseUrl: '/js'
});

after that this code will work, because it will concatenate baseUrl with your relative url.

require(['libs/jquery'], function ($) {
    $('#test').html('123');
});

Upvotes: 0

EsTeGe
EsTeGe

Reputation: 3065

If I configure a path

require.config({
    paths: {
        'jquery': 'libs/jquery'
    }
});

and change the require to:

require(['jquery'], function ($) {
    $('#test').html('123');
});

it appears to be working. If someone could explain me why.

Upvotes: 8

Related Questions