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");
});
});
Related
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",
}
});
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.
I'm using Webjars to import AngularJS into my web project.
For some reason the minified version of AngularJS won't be served even though I'm referencing those in my main. I was expecting to see angular.min.js and angular-route.min.js being loaded, but I'm seeing the regular angular.js and angular-route.js. What am I doing wrong here?
My main.js:
'use strict';
requirejs.config({
paths: {
'angular': '../lib/angularjs/angular.min',
'angular-route': '../lib/angularjs/angular-route.min',
'async': '../lib/requirejs-plugins/src/async'
},
shim: {
'angular': {
exports : 'angular'
},
'angular-route': {
deps: ['angular'],
exports : 'angular'
}
}
});
require(['angular', './controllers', './directives', './filters', './services', 'angular-route','./places-autocomplete','async','./gmaps'],
function(angular, controllers) {
initialize();
// Declare app level module which depends on filters, and services
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'ngRoute']).
config(['$routeProvider', function($routeProvider) {
....
}]);
angular.bootstrap(document, ['myApp']);
});
My html loads requirejs like this:
<script>
#Html(org.webjars.RequireJS.getSetupJavaScript(routes.WebJarAssets.at("").url))
</script>
<script data-main="#routes.Assets.versioned("javascripts/main.js")"
src="#routes.WebJarAssets.at(WebJarAssets.locate("require.min.js"))"></script>
and the above requirejs.config snippet resides in main.js
I looked into the sources of requirejs. Here's what I found:
requirejs splits each path, you defined in the config object, into its components (i.e. the directories, the filename and the extension). For some reason (node module naming conventions) the last extension is dropped. They do not check if that's a '.js'. Then this path array is used to access a module. Without a plugin rquirejs only handles .js files. It adds a .js if nessecary.
Now you can see what happens in your example. In the first step requirejs drops the .min extension. When it loads the module it joins the path components and adds a .js to the end. Then it loads the full module and not the minified version.
If you add a .js to your paths, then this .js was dropped and the .min is still there.
Try to add
enforceDefine: true,
Is possible to have requirejs config at one place and reuse it in modules?
such as
main.js:
requirejs.config({
baseUrl: "static/js",
paths: {
"jquery": "http://code.jquery.com/jquery-1.9.1.js",
"jquery-ui": "http://code.jquery.com/ui/1.10.2/jquery-ui.js"
},
shim: {
"jquery-ui": {
deps: ["jquery"]
}
}
});
and
public.js:
define(["main", "jquery", function(main, $) {
// do some public stuff
});
client.js:
define(["main", "jquery", function(main, $) {
// do some client stuff
});
And on my public part of web have
<script type="..." src="js/require.js" data-main="js/public.js"></script>
And on client part of web
<script type="..." src="js/require.js" data-main="js/client.js"></script>
And also I would like to have a module for each page. So for example to have a index module on public
<script ...>
require('public/index');
</script>
and
public/index.js:
define(["jquery", "slideshow"], function($, s) {
$( function() { s.init() } );
});
Is that possible with RequireJS?
Thank you for answers.
data-main is a useful shortcut in the very simple case but I don't find it terribly useful beyond that, the solution is to dump it entirely.
Load your main explicitly on each page, then use the callback to load your view-specific scripts.
So you have in public.html:
<script src="/Scripts/require.js"></script>
<script>
require('main', function(){
require('public');
})
</script>
and in client.html:
<script src="/Scripts/require.js"></script>
<script>
require('main', function(){
require('client');
})
</script>
I've written a blog post expounding on this idea here.
I edit my answer as you make the question clearer.
In any page you include require.js, you should also include main.js to define your RequireJS config.
You can't do things like
define(["main", "jquery", function(main, $) {
// do some public stuff
});
because ReuiqreJS load dependencies asynchronously. Although "main" is placed before "jquery", it's not guaranteed RequireJS will load them in that sequence.
So your public/index.html can be like:
<script type="..." src="js/require.js"></script>
<script type="..." src="js/main.js"></script>
<script ...>
require('public/index');
</script>
I am trying to load and use jQuery, I do not want to use the RequireJs+jQuery bundle because I am not planning to use the latest version.
However it seems the document ready event it is not getting executed,
require.config({
baseUrl: 'js/'
});
require([
"jquery.min",
"jquery.alpha",
"jquery.beta"
], function($) {
console.log('require js okay');
define(['jquery'], function ($) {
$(document).ready(function() {
console.log('jquery has loaded');
$('body').alpha().beta();
});
});
});
jQuery exports itself as a named module. This means you need to add a path to your config options to properly return jQuery as a module.
paths: {
"jquery": "js/jquery,
},