First off, I made a custom javascript file, main.js. Quite simple; it's just this:
$("#testp").text("Hello!");
#testp is in one of my phtml files, with just <p id="testp">Hello World!</p>.
Beforehand, just to let you know: jQuery is imported automatically by RequireJS because jquery.js is under the baseURL already. In the Chrome Firebug console, I can confirm this by typing jQuery and an object is sent back. However, the commonly used $ which I need to access jQuery is undefined. This is a problem because I have plenty of other libraries that use $ in place of jQuery keyword.
My questions are:
- How would I import main.js into RequireJS so that the script can be executed? If main.js runs successfully, I would expect the paragraph to show "Hello!" instead of "Hello World!"
- Main.js is dependent on jQuery. How would I make sure that jQuery will be accessible in main.js?
- The
jQuerykeyword returns an object while$does not. How can I configure jQuery to let $ be a global variable?
1 Answer 1
Require forces us to avoid global variables, if you want to use $ in your script you have to define it as a AMD module
define([
"jquery"
], function ($) {
// Here you can use $ with a local scope
});
Then declare your script in require-config.js
var config = {
map: {
'*': {
'Yourmodule':'path/to/main',
}
};
Explore related questions
See similar questions with these tags.