So, I built my RequireJS app using grunt-require, which I believe uses r.js behind the scenes. However, upon running the app, I get this every time:
Uncaught Error: Module name "underscore" has not been loaded yet for context: _. Use require([])
http://requirejs.org/docs/errors.html#notloaded require-2.1.9.min.js:8
GET http://localhost:8080/resources/js/app/App.js 404 (Not Found) require-2.1.9.min.js:34
Uncaught Error: Script error for: app/App
http://requirejs.org/docs/errors.html#scripterror
My "main" script is in app/Main.js and looks like this:
require(['common'], function() {
'use strict';
require(['app/App'], function(app) {
app.start();
});
});
And then the build options for grunt-require:
requirejs: {
options: {
baseUrl: 'resources/js',
dir: 'resources/js/build',
main: 'app/Main',
out: null,
optimize: 'uglify2',
skipDirOptimize: true,
priority: ['common'],
preserveLicenseComments: false,
modules: [
{
name: 'common'
},{
name: 'app/Main',
exclude: ['common'],
include: ['app/App']
}
],
paths: { ... },
shim: { ... }
}
}
As you can see, I've included app/App in the build of app/Main.js.
It loads Main.js and common.js separately, as expected, but then it tries to load app/App.js separately. When I look in the built version of Main.js, I see that app/App.js has in fact been built in.
Any ideas why it's trying to load app/App.js separately?
It seems, you forgot findNestedDependencies : true option in your build config and your nested require did not load. See its description.
Related
tl;dr
RequireJS optimizer doesn't like me defining bundle definitions on a module, but also does not find the modules if I don't define the bundles.
long version
I am getting the following error when trying to use the requirejs optimizer:
Error: Module loading did not complete for: scripts/simulation.bundle, app_mini, testservice
The following modules share the same URL. This could be a misconfiguration if that URL only has one anonymous module in it:
.../web/dist/scripts/app.bundle.js: app_mini, testservice
I am actually using grunt-contrib-requirejs to optimize my js scripts for production. It was all working fine before adding the simulator.bundle
I have 3 bundles:
app.bundle (main bundle)
simulation.bundle
vendor.bundle
This is the modules option of the requirejs grunt tasks
[{
name: 'scripts/vendor.bundle',
exclude: [],
override: {
paths: {
angular: 'bower/angular/angular',
jquery: 'bower/jquery/dist/jquery',
ngRoute: "bower/angular-route/angular-route"
},
shim: {
angular: {
exports: 'angular',
deps: ['jquery'] // make jquery dependency - angular will replace jquery lite with full jquery
},
bundles: {
'scripts/app.bundle': ['app_mini', 'testservice'],
},
}
}
},
{
name: 'scripts/simulation.bundle',
exclude: [],
override: {
paths: {},
shim: {},
bundles: {
'scripts/vendor.bundle': ['angular', 'jquery'],
'scripts/app.bundle': ['app_mini', 'testservice']
}
}
},
{
name: 'scripts/app.bundle',
exclude: ['scripts/vendor.bundle'],
override: {
paths: {
app_mini: 'scripts/app.mini',
testservice: 'scripts/features/test.service'
},
shim: {},
bundles: {
'scripts/vendor.bundle': ['angular', 'jquery']
}
}
}
]
The bundles in simulation.bundle seem to be the problem. However, if I remove them, the files cannot be found:
>> Error: ENOENT: no such file or directory, open
>> '...\web\dist\app_mini.js'
>> In module tree:
>> scripts/simulation.bundle
The simulation.bundle is just a dummy module, loading angular and app_mini:
define(['app_mini', 'angular'], function(app_mini, angular) {
// nothing here
}
So either way, the optimizer cannot process the dependencies. How do I have to configure it to make it work?
Alright, once again I am posting the answer to my own question, and I hope some other people will benefit from my mistakes ;)
So what I found out is:
Bundle config is only for requireJS and not for the optimizer!
The bundles I defined in the config are leading to the error of modules sharing the same url.
The right way to do it, is to define ALL the paths for ALL the modules, and to specifically exclude the modules by name that should not be included in a module.
For example, app_mini should go into the app.bundle, but because it is required in the simulation.bundle it would get included there, because excluding app.bundle is not yet possible (it has not been optimized at this point), we need to exclude app_mini directly.
So a working config would look like this: (not tested)
paths: {
angular: 'bower/angular/angular',
jquery: 'bower/jquery/dist/jquery',
ngRoute: "bower/angular-route/angular-route"
app_mini: 'scripts/app.mini',
testservice: 'scripts/features/test.service'
},
shim: {
angular: {
exports: 'angular',
deps: ['jquery'] // make jquery dependency - angular will replace jquery lite with full jquery
}
},
modules: [
{
name: 'scripts/vendor.bundle',
exclude: [],
},
{
name: 'scripts/simulation.bundle',
exclude: [`app_mini`],
},
{
name: 'scripts/app.bundle',
exclude: ['scripts/vendor.bundle'],
}
}]
I am using Karma to run tests against some code.
Both the tests and the code are transpiled (ES6 => ES5 using babel) before being run by Karma.
This works great and the tests run fine.
But if I try and use the text! plugin from any of the files being tested...
import template from 'text!./template.html';
...I get:
There is no timestamp for /base/src/text.js!
Uncaught Error: Script error for "text", needed by: text!app/template.html_unnormalized2
http://requirejs.org/docs/errors.html#scripterror
Uncaught Error: Load timeout for modules: text!app/template.html_unnormalized2
Does anyone have any ideas why this might be?
The built artifact in the dist folder (i.e. the item under test) contains the successfully encoded text RequireJS items eg:
define('text!app/template.html',[],function () { return '<div>foo</div>';});
Additional Info
test-main.js
var TEST_REGEXP = /(spec|test)\.js$/i;
var allTestFiles = [];
Object.keys(window.__karma__.files).forEach(function(file) {
if (TEST_REGEXP.test(file)) {
var normalizedTestModule = file.replace(/^\/base\/|\.js$/g, '');
allTestFiles.push(normalizedTestModule);
}
});
require.config({
baseUrl: '/base/src',
paths: {},
shim: {},
deps: allTestFiles,
callback: window.__karma__.start
});
karma.conf.js
module.exports = function(config) {
'use strict';
var path = require('path');
var cdn = 'http://localhost:55635/modules/';
var basePath = path.dirname(__filename);
config.set({
basePath: '../../..',
frameworks: [
'requirejs',
'jasmine'
],
files: [
{
pattern: path.join(basePath, 'test-transpiled', '*-spec.js'),
included: false
},
path.join(basePath, 'dist', 'artifacts', 'app.js'),
path.join(basePath, 'test', 'unit', 'test-main.js')
],
proxies: {
'/cdn/': cdn
},
exclude: [],
preprocessors: {},
reporters: ['dots'],
colors: true,
autoWatch: false,
singleRun: false,
browsers: ['Chrome'],
});
};
Edit:
I have added the following to karma.conf.js:
files: [
{
pattern: path.join(basePath, 'node_modules/require-plugins/text/text.js'),
included: false
},
// ...
],
I continue to get an error when running the tests:
There is no timestamp for /base/src/text.js!
Presumably because I need to add "text" to the paths section of test-main.js?
require.config({
baseUrl: '/base/src',
paths: {
'text': '../node_modules/require-plugins/text/text'
},
// ...
});
But I have tried various combinations of baseUrl and the path in the text path and I cannot get it to stop 404-ing.
Your files option in karma.conf.js does not include the text plugin, which is why you get the error that there's no timestamp for it.
Add an item to your files list that hits the text plugin on your file system, and make sure that you have included: false for it. RequireJS plugins are like other modules: RequireJS must be able to load them to use them.
You may need to also set paths in test-main.js depending on where you put your plugin. RequireJS already is looking for it at /base/src/text.js. If you locate it so that the plugin is served at this URL, then there's no need to set paths. If you put it somewhere else, then you do need to set paths. Something like:
paths: {
text: 'path/to/text',
}
Remember that the paths in paths are interpreted relative to your baseUrl setting.
I tried using the require.js text! plugin, and also found that it conflicts with the baseUrl defined for the rest of the project.
The requirejs.config sets the baseUrl to the parent directory of the JS files, while my templates are defined in a sibling directory to the js.
There was no way to tell requirejs to load templates from /base/templates and js from base/js.
My solution was to change the text.js plugin, and add a hook to change the url just before the ajax call is made to fetch the HTML file. You can take my version of text.js from here.
I am using on a backbonejs project with requirejs. I am using Gruntjs as build process. In this project I am using external underscore templates. Below is my dir structure.
MainApp/
app/
images/
js/
styles/
templates/
index.html
Below is my requirejs options in Gruntfile.js
requirejs: {
compile: {
options: {
name: "views/app",
baseUrl: "prod/js",
mainConfigFile: "prod/js/main.js",
out: "prod/scripts/scripts.min.js",
include: ['libs/requirejs/require.js']
}
}
}
However, this seems to be not working. When I build it by running grunt command it does build the project successfully i.e. I am not getting any errors during build process. But when I want to run this project in browser, it does not work. It shows the home page correctly with correct styles but javascript functionality is not working. One of the reason I can think of is I am using external templates which grunt requirejs plugin seems to be not picking up.
How can I use external templates?
UPDATE
I am using grunt-contrib-requirejs plugin.
RequireJS config file is nto included in output file. You must split config and main app:
src/js/config.js
/*global require:false */
require.config({
urlArgs: 'version=' + (new Date()).getTime(),
paths: {
'jquery' : 'libs/jquery/dist/jquery',
'underscore' : 'libs/underscore/underscore',
'backbone' : 'libs/backbone/backbone',
'localStorage' : 'libs/backbone.localStorage/backbone.localStorage',
'text' : 'plugins/text'
}
});
src/js/main.js
/*global require:false */
/*global Backbone:false */
/*global _:false */
require(['views/app', 'collections/todos', 'router'], function (AppView, TodoCollections, Router) {
window.App = {
Vent: _.extend({}, Backbone.Events)
};
new AppView({
collection: new TodoCollections()
});
window.App.TodoRouter = new Router();
Backbone.history.start();
});
Gruntfile.js
requirejs: {
compile: {
options: {
baseUrl: "dist/js",
mainConfigFile: "dist/js/config.js",
name: 'main',
out: "dist/scripts/scripts.min.js",
include: 'libs/requirejs/require.js',
optimize: 'none',
preserveLicenseComments: false,
useStrict: true,
wrap: true
}
}
},
I'm trying to modularize my existing project by breaking out functionality into separate applications that share a lot of common code. It's a Backbone/Marionette app, and everything is working fine in development mode, but I'm having trouble getting optimization to work. I currently have two pages, with 2 main files and 2 application files. The main files both contain requirejs.config blocks which are almost identical, except the second one uses the map config option to map the app module to loginApp. The reason for this is that most of the other modules depend on the app module for some application-wide functionality, including messaging and some global state variables.
main.js:
requirejs.config({
shim: { ... },
paths: { ... }
});
define(['vendor'], function() {
// This loads app.js
require(['app'], function(Application) {
Application.start();
});
});
main-login.js:
requirejs.config({
shim: { ... },
paths: { ... },
map: {
"*": { "app": "loginApp" }
}
});
define(['vendor'], function() {
// This loads loginApp.js because of the mapping above
require(['app'], function(Application) {
Application.start();
});
});
This works great until I optimize. I'm getting an error about a missing file, but having worked with requirejs long enough, I know that really has nothing to do with the problem. :)
From the docs:
Note: when doing builds with map config, the map config needs to be
fed to the optimizer, and the build output must still contain a
requirejs config call that sets up the map config. The optimizer does
not do ID renaming during the build, because some dependency
references in a project could depend on runtime variable state. So the
optimizer does not invalidate the need for a map config after the
build.
My build.js file looks like this:
({
baseUrl: "js",
dir: "build",
mainConfigFile: "js/main.js",
removeCombined: true,
findNestedDependencies: true,
skipDirOptimize: true,
inlineText: true,
useStrict: true,
wrap: true,
keepBuildDir: false,
optimize: "uglify2",
modules: [
{
name: "vendor"
},
{
name: "main",
exclude: ["vendor"]
},
{
name: "main-login",
exclude: ["vendor"],
override: {
mainConfigFile: "js/main-login.js",
map: {
"*": {
"app": "loginApp"
}
}
}
}
]
});
I'd like to avoid having 2 separate build files, if possible, and I'm working on breaking out the requirejs.config block into a single, shared file and having the 2 main files load that and then load the app files (this is similar to how the multipage example works) but I need that map config to work in the optimizer in order for this to work. Any ideas what I'm missing here?
Update
I've split out the config into its own file, config.js, which gets included by the main-* files. In the main-login.js file, I include the map config above the define and everything works in development mode.
require.config({
map: {
"*": {
"app": "loginApp"
}
}
});
define(['module', 'config'], function(module, config) {
...
The build.js file is the same as above, except with the second mainConfigFile removed. Optimization still fails, though. What I think is happening is, since this is a Marionette app, it's common practice to pass the Application object as a dependency to other parts of the app, including views, controllers and models. When I optimize, I run into two different problems. If I leave removeCombined as true, the optimizer will build in the dependencies from the first app, then remove those files, so when it sees them in the second app, it will fail because it can't find the source files anymore. Setting this to false seems reasonable, but the problem is this then gives me the following error:
Error: RangeError: Maximum call stack size exceeded
I can't find any consistent information on this particular error. It might have something to do with the hbs plugin (similar to text but for pre-compiling Handlebars templates) but I'm not positive that's the case. Since there's no stack trace, I'm not sure where to start looking. My gut feeling is it's a circular dependency somewhere, though. So, my updated question is, how should a multi-page Marionette app be decoupled so as to make sharing code (not just 3rd party code, but custom code such as data models and views) possible? Do I need to remove any dependencies on the core Application object? (That would require an awful lot of refactoring.) Since it works just fine in development mode, is there some trick to r.js's config I'm overlooking? I've tried adding app to the exclude lists as well as stubModules but nothing seems to work. I'm thinking of just creating 2 build files and being done with it, but I'd really like to know how to solve this the "right" way.
Your build file can be like this:
({
...
include: [ './config/main.js' ],
pragmasOnSave: {
excludeBuildConfig: true
}
})
You can use pragmasOnSave to tell optimizer to exclude a section in a file in optimized result, so Requirejs config file can be like following code
requirejs.config({
//>>excludeStart('excludeBuildConfig', pragmas.excludeBuildConfig)
shim: { ... },
paths: { ... },
//>>excludeEnd('excludeBuildConfig')
map: {
"*": { "app": "loginApp" }
}
});
The final solution used was to incorporate Grunt into the build workflow. Inside Grunt, I'm dynamically creating task targets to the requirejs task. I refactored my multiple applications to all use the same folder structure, so it was easy to reuse the same build config for each. There's still the minor inconvenience of compiling the vendor file multiple times, but that's a small price to pay.
Here's the function I use to create the config inside my dev task, in case anyone's interested:
var buildRequireTargets = function(appList) {
var requireTargets = {},
buildConfig = {
baseUrl: "<%= sourceDir %>/js",
dir: "<%= buildDir %>/js",
mainConfigFile: "<%= sourceDir %>/js/config.js",
removeCombined: true,
findNestedDependencies: true,
skipDirOptimize: true,
inlineText: true,
useStrict: true,
wrap: true,
keepBuildDir: true,
optimize: "none",
pragmasOnSave: {
excludeHbs: true
}
};
_.each(appList, function (app) {
requireTargets[app] = {
options: _.extend({
map: {
"*": {
"app": app + "/app"
}
},
modules: [
{
name: "vendor"
},
{
name: app + "/main",
exclude: ["vendor"]
}
]
}, buildConfig)
};
});
grunt.config("requirejs", requireTargets);
};
Good afternoon,
I'm trying to optimize a source code based on Require.js and Backbone using r.js but I'm getting the following error during the compilation :
Tracing dependencies for: main
Cannot optimize network URL, skipping: empty:.js
TypeError: Cannot read property 'normalize' of undefined
In module tree:
main
app
router
views/main_panel/event_details
helpers/template_manager
My template_manager module does not try to access any 'normalize' property so I don't really understand what is that supposed to mean.
Here's the entry point to my application as well as the require.js configuration.
require.config({
paths: {
order: 'libs/requirejs-plugins/order',
text: 'libs/requirejs-plugins/text',
jQuery: 'libs/jquery/jquery',
Underscore: 'libs/underscore/underscore',
Backbone: 'libs/backbone/backbone',
templates: '../templates',
Sync: 'helpers/sync'
}
});
require([
'app',
'event_manager',
'order!https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js',
'order!libs/underscore/underscore-min',
'order!libs/backbone/backbone-min',
'helpers/objects_extension',
'helpers/date_extension',
'helpers/assets'
], function(App){
App.initialize();
});
The application itself more or less follows what's in this tutorial.
My app.build.js file is as follow
({
appDir: "../",
baseUrl: "js",
dir: "../app-build",
modules: [
{
name: "main"
}
],
paths: {
order: 'empty:',
text: 'empty:',
jQuery: 'empty:',
Underscore: 'empty:',
Backbone: 'empty:',
templates: '../templates',
Sync: 'helpers/sync'
}
})
Thank you for your help.
James Burke says:
The text plugin needs be loaded by the loader for it to process text! depenencies. Loader plugins are executed as part of a build to resolve their resources.
So it should be enough to remove the text: "empty:" from the paths config, and just leave the excludes: in so it is not included in the final build result. This assumes you have text.js available locally to be read by the optimizer.
https://github.com/jrburke/r.js/issues/221