RequireJS Setting Path to the Parent Level - javascript

In order to direct my models, collections, etc. from my mobile app to my web app, I need to configure my RequireJS.
I have the following file structure:
/
/js
/models
/mobile
/js
/templates
I want my mobile app to use my main app's models, so I set the following:
require.config( {
paths : {
models : '/js/models',
templates : 'mobile/templates'
}
});
And I get these errors in Chrome:
Uncaught SyntaxError: Unexpected token < /mobile/js/models/User.js?bust=0.1.0:1
Uncaught SyntaxError: Unexpected token < /mobile/js/models/InviteRequest.js?bust=0.1.0:1
Uncaught SyntaxError: Unexpected token < /mobile/js/models/Log.js?bust=0.1.0:1
Meaning that it's still looking in /mobile instead of /.
This path config works for my templates folder, but not my models folder. How can I point all require dependencies that start with models/ to my main models folder?
Thanks!
ATTEMPT 2
I tried setting the baseUrl instead:
require.config( {
baseUrl : '/',
paths : {
views : 'mobile/views',
templates : 'mobile/templates'
}
});
require( [
'app'
],
function(App) {
App.initialize();
});
I get the error:
GET http://local.m.mysite.co/app.js 404 (Not Found) require.js:2

In your second attempt, you basically tell Require JS to load 'app' module and since you set the base url to '/', Require JS will look 'app' module in your root path.
So what you need to do is to tell Require JS where to look for your 'app' module. Say your 'app' module is in /js/module:
/
/js
/models
/module
/app.js
/mobile
/js
/templates
Then your code to load 'app' module is:
require.config( {
baseUrl : '/',
paths : {
views : 'mobile/views',
templates : 'mobile/templates'
}
});
require( [
'js/module/app'
],
function(app) {
app.initialize();
});
Alternatively, you can set 'module' path in your config. Then refer to this path in your dependency loading:
require.config( {
baseUrl : '/',
paths : {
views : 'mobile/views',
templates : 'mobile/templates',
module: 'js/module'
}
});
require( [
'module/app'
],
function(app) {
app.initialize();
});
As for the error you get in Chrome before your ATTEMPT 2, you will need to look at how you refer to your module in module loading.

Related

gulp-angular-templatecache Module is not available

I am using gulp-angular-templacache.
I have that task that should create a module named templates and I added it as a dependency to my app module:
Configurations:
templateCache: {
file: 'tempaltes.js',
options: {
module: 'templates',
standalone: true,
root: 'app/'
}
}
App module:
var App = angular.module('app', [
'templates']);
Gulp task:
gulp.task('templatecache', ['clean-code'], function() {
log('Creating AngularJS $templateCache');
return gulp
.src(config.htmltemplates)
.pipe($.minifyHtml({empty: true}))
.pipe($.angularTemplatecache(
config.templateCache.file,
config.templateCache.options
))
.pipe(gulp.dest(config.temp));
});
But, when I try to run this I am always getting that error message:
Uncaught Error: [$injector:nomod] Module 'templates' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
I tried to make the templatescache also not standalone and removing the dependency but without success...
What should I do ??
Seems you are loading template.js, after the module app definition. You can load the file before your angular app file
OR, Don't define a standalone module.
Configuration
templateCache: {
file: 'tempaltes.js',
options: {
module: 'templates',
standalone: false,
root: 'app/'
}
}
Angualr
//Define the module
angular.module('templates', []);
var App = angular.module('app', ['templates']);

Include file with module from AngularJS app into RequireJS config file in Karma

As we know, when use RequireJS in the configuration file we must define 'paths' and 'shim'. When writing tests (Karma, Jasmine), we need to create an additional configuration file for RequireJS and re-define the same data.
I try to extract common parts and load them dynamically. In Angular JS application, everything works without problems, but in test i have always error '404'. But let's get to the beginning. Simple example structure:
.
|-- newApp
| |-- app
| | `-- app.require.js
| |-- newApp.require.js
| `-- index.html
`-- test
|-- test.karma.js
`-- test.require.js
index.html load RequireJS config file
<script data-main="newApp.require.js" src="bower_components/requirejs/require.js"></script>
newApp.require.js init RequireJS
require([
'app/app.require'
], function (appRequire) {
"use strict";
require.config({
baseUrl: 'app',
paths: appRequire.paths,
shim: appRequire.shim,
deps: [
'NewAppBootstrap'
]
});
});
app.require.js Module / object with paths and shim
define([
'some/others/components.require'
], function (componentsRequire) {
"use strict";
var appRequire = {
'NewApp': 'app.module',
'NewAppBootstrap': 'app.bootstrap',
'NewAppRoute': 'app.routes'
};
var vendorRequire = {
'jQuery': {
exports: '$'
},
'angular': {
exports: 'angular'
}
};
return {
paths: Object.assign(
appRequire,
componentsRequire
),
shim: vendorRequire
};
});
Up to this point everything works fine. Now I would like to file app.require.js load into test.require.js. And the problems begin...
test.require.js
var TEST_REGEXP = /(spec|test)\.js$/i;
var allTestFiles = [];
Object.keys(window.__karma__.files).forEach(function (file) {
'use strict';
if (TEST_REGEXP.test(file)) {
var normalizedTestModule = file.replace(/^\/base\/|\.js$/g, '');
allTestFiles.push(normalizedTestModule);
}
});
require([
'app/app.require'
], function (appRequire) {
"use strict";
require.config({
baseUrl: '/base/newApp',
waitSeconds: 200,
paths: appRequire.paths,
shim: appRequire.shim,
deps: allTestFiles,
callback: window.__karma__.start
});
});
Unfortunately, I still have error:
WARN [web-server]: 404: /app/app.require.js
PhantomJS 2.1.1 (Linux 0.0.0) ERROR: 'There is no timestamp for app/app.require.js!'
PhantomJS 2.1.1 (Linux 0.0.0) ERROR
Error: Script error for "app/app.require"
http://requirejs.org/docs/errors.html#scripterror at node_modules/requirejs/require.js:143
I tried different paths, but still nothing. Does anyone know how to load this file? Whether it is at all possible load file in this place? I would be grateful for any tips.
By the time your code hits this require call:
require([
'app/app.require'
],
There is no RequireJS configuration in effect, and data-main is not used, so by default RequireJS takes the directory that contains the HTML page that loads RequireJS as the baseUrl (See the documentation.) Since index.html sits at the root, then RequireJS resolves your module name to /app/app.require.js and does not find it.
You can work around it by using a full path:
require([
'base/newApp/app/app.require'
],
Or if it so happens that other code later is going to try to access this same module as app/app.require, then you should have a minimal configuration before your first require call:
require.config({
baseUrl: '/base/newApp',
});
It is perfectly fine to call require.config multiple times. Subsequent calls will override values that are atomic (like baseUrl) and marge values that can be merged. (An example of the latter would be paths. If the first call sets a paths for the module foo and a 2nd call sets a paths for the module bar, then the resulting configuration will have paths for both foo and bar.)

Unit testing AngularJS application with karma-browserify

I'm trying to unit test an AngularJS/Browserify application via karma-browserify. Ultimately, when I run my gulp karma task, I get the error Error: [$injector:nomod] Module 'myApp' is not available! You either misspelled the module name or forgot to load it...
My gulpfile.js has the task
gulp.task('test', function(done) {
new karma.Server({
configFile: __dirname + '/karma.conf.js'
}, done).start();
});
My karma.conf.js includes
{
// ...
frameworks: ['browserify', 'jasmine'],
files: [
'node_modules/angular/angular.js',
'node_modules/angular-mocks/angular-mocks.js',
'spec/**/*.js'
],
preprocessors: {
'spec/**/*.js': [ 'browserify' ]
},
browserify: {
debug: true
}
// ...
}
I define my module in a main.js that includes
require('angular').module('myApp', [
//...lots of `require`s for each dependency...
]);
I define my controller in a MainCtrl.js that looks like
function MainCtrl(/*...deps...*/) {
var ctrl = this;
ctrl.foo = 'bar';
}
module.exports = MainCtrl;
then register the controller elsewhere like
var app = require('angular').module('myApp');
app.controller('MainCtrl', [/*...deps...*/, require('./MainCtrl')]);
Finally my test looks like
(function() {
"use strict";
describe('MainCtrl', function() {
var ctrl;
beforeEach( angular.mock.module('myApp') );
beforeEach( inject( function($controller) {
ctrl = $controller('MainCtrl');
}));
it('should be defined', function() {
expect(ctrl).toBeDefined();
});
});
}());
Workaround
The workaround I have is to add my main.js file to karma.conf.js
files: [
'js/main.js', // ADDED: Defines the app and `require`s angular
'node_modules/angular-mocks/angular-mocks.js',
'spec/**/*.js'
],
preprocessors: {
'js/main.js': ['browserify'], // ADDED
'spec/**/*.js': ['browserify']
}
and everything works. But I thought I wasn't supposed to add my source files to karma (at least not with karma-browserify). Is this the right way to set up my project?
Yes, the 'workaround' is the desired way to use karma-browserify.
preprocessors definition specifies which of the included files should be processed by which preprocessor but does not include them:
The keys of the preprocessors config object are used to filter the
files specified in the files configuration.
it is files definition that actually includes the files:
The files array determines which files are included in the browser and
which files are watched and served by Karma.
Files tells Karma which files it should load relative to the base path. These are:
All test related libraries
Our source code to test
The tests themselves

How to build requirejs app with webpack?

I have a requirejs app which gets loaded from the require config pasted below. The path references to the vendor directory are 3rd party libraries loaded via bower.
// Require.js Configurations
// -------------------------
require.config({
baseUrl: './js/app',
paths: {
'backbone' : '../../vendor/backbone/backbone',
'backbone.paginator' : '../../vendor/backbone.paginator/lib/backbone.paginator',
'backbone.validateAll': '../../vendor/Backbone.validateAll/src/javascripts/Backbone.validateAll.js',
'backbone.wreqr' : '../../vendor/backbone.wreqr/lib/backbone.wreqr.js',
'handlebars' : '../../vendor/handlebars/handlebars.runtime',
'handlebars-helpers' : '../../vendor/handlebars-helpers/src/helpers',
'jasminejquery' : '../../vendor/jasmine-jquery/lib/jasmine-jquery',
'jquery' : '../../vendor/jquery/dist/jquery',
'jquerymobile' : '../../vendor/jquery-mobile-bower/js/jquery.mobile-1.4.5',
'loglevel' : '../../vendor/loglevel/lib/loglevel',
'marionette' : '../../vendor/marionette/lib/backbone.marionette',
'modernizr' : '../../vendor/modernizr/modernizr',
'moment' : '../../vendor/moment/moment',
'swiper' : '../../vendor/swiper/dist/idangerous.swiper',
'templates/jst' : '../../build/tmp/templates/jst-build',
'underscore' : '../../vendor/lodash/dist/lodash'
},
shim: {
'backbone.validateAll' : ['backbone'],
'jasminejquery' : ['jquery'],
'jquerymobile' : ['jquery'],
'modernizr' : { exports: 'Modernizr' },
'swiper' : ['jquery']
}
});
// Bootstraps
require(['bootstrap/backbone'], function(){});
require(['bootstrap/jquery'], function(){});
// App
require(['init/Main'], function(main) {});
The issue I'm getting in my console says that my bootstrap files are not found which only leads me to believe that webpack is not loading in my require.config.
$ webpack ./app/config/requirejs.js ../build/test.js Hash: f33deaf4b2ff288e08b6 Version: webpack 1.5.3 Time: 61ms Asset Size
Chunks Chunk Names test.js 2435 0 [emitted] main
[0] ./app/config/requirejs.js 1691 {0} [built] [3 errors]
ERROR in ./app/config/requirejs.js Module not found: Error: Cannot
resolve module 'bootstrap/backbone' in
/Users/glitches/Sites/public/js/app/config #
./app/config/requirejs.js 35:0-45
ERROR in ./app/config/requirejs.js Module not found: Error: Cannot
resolve module 'bootstrap/jquery' in
/Users/glitches/Sites/public/js/app/config #
./app/config/requirejs.js 36:0-43
ERROR in ./app/config/requirejs.js Module not found: Error: Cannot
resolve module 'init/Main' in
/Users/glitches/Sites/public/js/app/config #
./app/config/requirejs.js 39:0-41
I'm guessing I need to rewrite my requirejs configuration as an entry point but I'm asking here incase anyone has a better idea of how to go about this.
Your require statements are trying to resolve as modules in your node_modules folder, because there is no absolute or relative path.
How modules are resolved, depending on path type.
If you are requiring files within your application's source, use a relative or absolute path.
// Bootstraps
require(['../bootstrap/backbone'], function(){});
require(['../bootstrap/jquery'], function(){});
// App
require(['../init/Main'], function(main) {});
This assumes a structure where this is at /app/config/requirejs.js and your target modules are at /app/bootstrap/backbone.js, /app/bootstrap/jquery.js, and /app/init/Main.js.

Optimizer and Handlebars client-side jade templates

I have an issue when trying to optimize client scripts that use client-side jade templating. Initially, I had an error as described in Require.js + Backbone optimization, but then I removed the "text" module from the paths configuration, added it to excludes and made text.js available locally. After doing that, I get an error where the optmizer tries to resolve the parameter being passed to the text module.
Here's my client-side template:
define([
'Handlebars',
'text!/templates/product/something.jade'
], function(Handlebars, txtSomething) {
var template = Handlebars.template,
templates = Handlebars.templates = Handlebars.templates || {};
templates['something'] = Handlebars.compile(txtSomething);
});
And then the optimizer configuration:
({
baseUrl: ".",
name: "product",
out: "product.js",
paths: {
Handlebars: "empty:"
},
exclude: ["text"]
})
And the error I get:
Error: ENOENT, no such file or directory 'C:\templates\product\something.jade'
In module tree:
product
modules/something
templates/something
text
Any advice on how to resolve the issue?
I precompile the handlebars templates before running optimization. that removes the text references

Categories

Resources