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?
asked May 7, 2017 at 16:03

1 Answer 1

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',
 }
};
answered May 19, 2017 at 20:12

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.