1

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:

  1. 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!"
  2. Main.js is dependent on jQuery. How would I make sure that jQuery will be accessible in main.js?
  3. The jQuery keyword returns an object while $ does not. How can I configure jQuery to let $ be a global variable?
0

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',
        }
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.