RequireJS is not loading modules relative to the baseUrl - javascript

In the <head> tag
<script>
var require = {
baseUrl: '/dist/js',
paths: {
jquery: 'jquery-1.11.3'
}
};
</script>
<script data-main="main.js" src="/dist/js/require.js></script>
And in main.js:
define(["exports", "jquery", "order.js", "search.js"], function (exports, _jquery, _orderJs, _searchJs) {
"use strict";
console.log("Hello");
});
Now, main.js loads just fine, same with jquery. But order.js and search.js is being loaded from the root (http://example.com/order.js).
Why is it not loading from the baseUrl?

Remove the .js extension from the module names you give to define or require. If you put the extension yourself, then RequireJS assumes the module name is a literal path and will skip your configuration.

Related

RequireJS: Reading configuration from app.js

In app.js, I am writing configurations for my project.I want to pick the version number of jquery from some external file config.js instead of hard coding it in app.js. How can I achieve this?
I have pasted code for app.js, config.js and index.html below:
config.js
define(function() {
var Config = {
jquery: "3.1.0"
};
return Config;
});
Index.html:
<script src="require.js" data-main="js/app"></script>
app.js
requirejs.config({
paths: {
jquery: serverUrl + "/jquery-3.1.0.min",
}
});
I cannot move requirejs.config() to config.js file as serverUrl is the variable used which I can't retrieve from config.js according to my project structure.
The easiest way to do what you want would just be to load a configuration file before your app.js and refer to it.
<script src="config.js"></script>
<script src="require.js" data-main="js/app"></script>
config.js could contain:
window.fooConfig = {
serverUrl: 'some appropriate URL',
}
I use window explicitly to make it clear I'm putting something in the global space on purpose. fooConfig for the name is just an example of what could be used for an application named foo. You can select something as unique as you need to avoid a clash with other code.
Then your app.js would do:
requirejs.config({
paths: {
jquery: fooConfig.serverUrl + "/jquery-3.1.0.min",
}
});

Having trouble setting up RequireJS

I'm trying to get a basic require JS app working but I'm having some difficulties, could someone help please? I'm using Laravel as well.
Include script
<body>
#yield('content')
<script data-main="{{ asset('/js/main.js') }}" src="{{ asset('/js/require.js') }}"></script>
</body>
config.js
require.config({
baseUrl: "",
paths: {
"jquery": "jquery-2.1.3.min"
}
});
main.js
require(['config'], function() {
define(['jquery'], function($) {
$(document).ready(function()
{
alert("test");
});
});
});
Folder directory structure:
/public
-- /js
-- -- jquery-2.1.3.min.js
-- -- config.js
-- -- main.js
-- -- require.js
The error I get is:
Uncaught Error: Mismatched anonymous define() module: function () {
alert("test");
}
define() wrapper supposed to wrap a module, not nested inside any code block. In your case it is child of a require() wrapper.
And your main.js file supposed to be the config file. Because require.js will load it for the dependency list as first task in order to init and inject the other dependencies for your app.
There are 2 ways for you to do this.
Use seperate files (like your way)
main.js
require.config({
baseUrl: "",
paths: {
"jquery": "jquery-2.1.3.min",
"app" : "main_module"
},
deps: 'app'
});
main_module.js
define(['jquery'], function($) {
$(document).ready(function(){
alert("test");
});
});
Or put your config into your main.js. Then write your code inside
require.config({
baseUrl: "",
paths: {
"jquery": "jquery-2.1.3.min"
}
});
require(['jquery'], function($) {
$(document).ready(function(){
alert("test");
});
});

require.js, am I doing it right?

I'm new to require.js and found the documentation quite hard to understand. After a while I got my project up and running with the following setup.
project
|
|--js
|--vendor
|--require.js
|--modernizr.js
|--jquery.js
|--modules
|--module1.js
|--module2.js
|--main.js
|--index.html
index.html:
<!DOCTYPE html>
<html>
<head></head>
<body>
<script data-main="/js/main.js" src="/js/vendor/require.js"></script>
</body>
</html>
main.js
define([
"vendor/modernizr",
"modules/module1",
"modules/module2"
]);
modules/module1.js
define(['vendor/jquery'], function () {
// Some module code like
$('#button').on('click', function(){});
});
Is this a good setup if I like to have one import file (main.js) like in a less setup for CSS?
This setup is generally in the right direction, just some slight modifications need to be made.
For the modules, you need to pass in a matching number of arguments for each dependency of the module. In this case, you would want to assign $ to what is returned by the jQuery module, so that you can actually use $ within the module:
define(['vendor/jquery'], function ($) {
// Some module code like
$('#button').on('click', function(){});
});
For main.js, the define() call should be a require() call so that you will be executing whatever's in the module instead of simply registering it a module for some other module to execute:
require([
"vendor/modernizr",
"modules/module1",
"modules/module2"
], function(Modernizr, module1, module2) {
// do something with Modernizr, module1, module2
});

Require JS is ignoring my config

I'm having pretty simple directory structure for scripts:
/js/ <-- located in site root
libs/
jquery-1.10.1.min.js
knockout-2.2.1.js
knockout.mapping.js
models/
model-one.js
model-two.js
...
require.js
config.js
Since the site engine uses clean URLs I'm using absolute paths in <script>:
<script type="text/javascript" data-main="/js/config.js" src="/js/require.js"></script>
RequireJS config:
requirejs.config({
baseUrl: "/js/libs",
paths: {
"jquery": "jquery-1.10.1.min",
"knockout": "knockout-2.2.1",
"komapping": "knockout.mapping"
}
});
Somewhere in HTML:
require(["jquery", "knockout", "komapping"], function($, ko, mapping){
// ...
});
So the problem is that RequireJS completely ignores baseUrl and paths defined in config file. I get 404 error for every module required in the code below. I see in browser console that RequireJS tries to load these modules from /js/ without any path translations:
404: http://localhost/js/jquery.js
404: http://localhost/js/knockout.js
404: http://localhost/js/komapping.js
However after the page is loaded and the errors are shown I type in console and...
> require.toUrl("jquery")
"/js/libs/jquery-1.10.1.min"
Why so? How to solve this problem?
It's my first experience using RequireJS, so I'm feeling like I've skipped something very simple and obvious. Help, please.
Update
Just discovered this question: Require.js ignoring baseUrl
It's definitely my case. I see in my Network panel that config.js is not completely loaded before require(...) fires own dependency loading.
But I don't want to place my require(...) in config because it is very specific for the page that calls it. I've never noticed such problem with asynchronicity in any example seen before. How do authors of these examples keep them working?
Solved.
The problem was that config file defined in data-main attribute is loaded asynchronously just like other dependencies. So my config.js accidentally was never completely loaded and executed before require call.
The solution is described in official RequireJS API: http://requirejs.org/docs/api.html#config
... Also, you can define the config object as the global variable require before require.js is loaded, and have the values applied automatically.
So I've just changed my config.js to define global require hash with proper configuration:
var require = {
baseUrl: "/js/libs",
paths: {
"jquery": "jquery-1.10.1.min",
"knockout": "knockout-2.2.1",
"komapping": "knockout.mapping"
}
};
and included it just BEFORE require.js:
<script type="text/javascript" src="/js/config.js"></script>
<script type="text/javascript" src="/js/require.js"></script>
This approach allows to control script execution order, so config.js will always be loaded before next require calls.
All works perfectly now.
Fixed the issue.
My config was being loaded asynchronously, and therefore the config paths weren't set before my require statement was being called.
As per the RequireJS docs Link here, I added a script call to my config before the require.js call. And removed the data-main attribute.
var require = {
baseUrl: '/js',
paths: {
'jquery': 'vendor/jquery/jquery-2.0.3.min',
'picker': 'vendor/pickadate/picker.min',
'pickadate': 'vendor/pickadate/picker.date.min'
},
shim: {
'jquery': {
exports: '$'
},
'picker': ['jquery'],
'pickadate': {
deps: ['jquery', 'picker'],
exports: 'DatePicker'
}
}
}
All is now working

RequireJS plugin( order.js )

http://requirejs.org/
I recently downloaded require.js 2.0 and I am getting error in my console:
Uncaught TypeError: Object function (){var g=ga.call(arguments,0),e;if(f&&v(e=g[g.length-1]))e.__requireJsBuild=!0;g.push(d);return b.apply(null,g)} has no method 'nameToUrl'
Is order.js plugin still supported by requirejs? I don't see its documentation in the website.
When I try to remove the file the script breaks.
In my index file, I included requirejs script in the head section:
<!DOCTYPE html>
<html>
<head>
<title>
My Mobile Application
</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" />
<link rel="stylesheet" href="public/css/style.css" />
<script data-main="scripts/main.js" src="scripts/require.js"></script>
</head>
<body></body>
</html>
Then in my main.js file:
requirejs.config({
//By default load any module IDs from js/lib
baseUrl: 'js/lib',
//except, if the module ID starts with "app",
//load it from the js/app directory. paths
//config is relative to the baseUrl, and
//never includes a ".js" extension since
//the paths config could be for a directory.
paths: {
app: '../app',
assets: '../assets',
views: '../app/views',
templates: '../app/templates',
collections: '../app/collections',
models: '../app/models'
}
});
// Start the main app logic.
requirejs([
'jquery/jquery',
'assets/jqm.config',
'jquery/mobile',
'text'
]);
require([
'app'
],
function( App ){
$(document).ready( function(){
App.initialize();
});
}
);
I sees to it that App.initialize doesn't have any errors and what App.initialize is doing is just simple geo location. The requirejs simply ask for order.js, and when I put the code it's having the same error as mentioned above.
Thank you!
Your assumption that order is no longer supported is correct. It was removed in favour of the shim configuration option:
So, the the order plugin has been removed and following the lead of
Tim Branyen and Dave Geddes, of use and wrap respectively, requirejs
2.0 integrates that kind of dependency tree specification directly in requirejs.
Require 2.0 upgrade notes - https://github.com/jrburke/requirejs/wiki/Upgrading-to-RequireJS-2.0
Also, check the shim documentation on the RequireJS site - http://requirejs.org/docs/api.html#config-shim
Oh figured it out.
//This is our main applicatoon boot loader or bootstrap
//here we are loading necessary scripts dependencies like
//jquery, jqm.config, mobile, text
requirejs.config({
baseUrl: 'js/libs',
//except, if the module ID starts with "app",
//load it from the js/app directory. paths
//config is relative to the baseUrl, and
//never includes a ".js" extension since
//the paths config could be for a directory.
paths: {
app: '../app',
assets: '../assets',
views: '../app/views',
templates: '../app/templates',
collections: '../app/collections',
models: '../app/models'
}
});
// Start the main app logic.
require(["jquery","assets/jqm.config","jquery/mobile","text","app"],
function(
$,
config,
mobile,
text,
App
) {
//the jquery.alpha.js and jquery.beta.js plugins have been loaded.
$(function() {
App.initialize();
});
});

Categories

Resources