I need some help because i'm fairly new to javascript and nodejs world and i'm stuck..
I have a nodejs app project where I installed dependencies (npm install) and then in my .js file, I load my modules like : var Backbone = require('backbone') and it works well.
But then i tried to install Backbone.DOMStorage (https://github.com/mikeedwards/Backbone.DOMStorage) module...
I did npm install https://github.com/mikeedwards/Backbone.DOMStorageand installation was Ok (js file is present in the node_modules folder), but when I try to load it with require('Backbone.DOMStorage') it failed to find and load the module...
From what I understood after many searches, it seems that the plugin isn't CommonJS compliant..
So how can I transform this script to be able to use it like any other module ??
Thanks !
I will show you 4 ways do what you want.
First way
Its a js plugin that's why you need to add it to your HTML page like this.
Include Backbone.domStorage after having included Backbone.js:
<script type="text/javascript" src="backbone.js"></script>
<script type="text/javascript" src="backbone.domStorage.js"></script>
and use it like this
window.SomeCollection = Backbone.Collection.extend({
localStorage: new Backbone.LocalStorage("SomeLocalCollection"), // Unique name within your app.
// ... everything else is normal.
});
Second way
If you're using browserify.
Install using npm install backbone.localstorage, and require the module.
Backbone.LocalStorage = require("backbone.localstorage");
third way
RequireJS
Include RequireJS:
<script type="text/javascript" src="lib/require.js"></script>
RequireJS config:
require.config({
paths: {
jquery: "lib/jquery",
underscore: "lib/underscore",
backbone: "lib/backbone",
localstorage: "lib/backbone.localStorage"
}
});
Define your collection as a module:
define("SomeCollection", ["localstorage"], function() {
var SomeCollection = Backbone.Collection.extend({
localStorage: new Backbone.LocalStorage("SomeCollection") // Unique name within your app.
});
return SomeCollection;
});
Require your collection:
require(["SomeCollection"], function(SomeCollection) {
// ready to use SomeCollection
});
forth way
Download js file from GitHub and put it to your library files directory after require it us js file like this
var domStorage = requier('yourLibPath/backbone.domStorage.js');
Related
I use the FayeJS and the latest version has been modified to use RequireJS, so there is no longer a single file to link into the browser. Instead the structure is as follows:
/adapters
/engines
/mixins
/protocol
/transport
/util
faye_browser.js
I am using the following nodejs build script to try and end up with all the above minified into a single file:
var fs = require('fs-extra'),
requirejs = require('requirejs');
var config = {
baseUrl: 'htdocs/js/dev/faye/'
,name: 'faye_browser'
, out: 'htdocs/js/dev/faye/dist/faye.min.js'
, paths: {
dist: "empty:"
}
,findNestedDependencies: true
};
requirejs.optimize(config, function (buildResponse) {
//buildResponse is just a text output of the modules
//included. Load the built file for the contents.
//Use config.out to get the optimized file contents.
var contents = fs.readFileSync(config.out, 'utf8');
}, function (err) {
//optimization err callback
console.log(err);
});
The content of faye_browser.js is:
'use strict';
var constants = require('./util/constants'),
Logging = require('./mixins/logging');
var Faye = {
VERSION: constants.VERSION,
Client: require('./protocol/client'),
Scheduler: require('./protocol/scheduler')
};
Logging.wrapper = Faye;
module.exports = Faye;
As I under stand it the optimizer should pull in the required files, and then if those files have required files, it should pull in those etc..., and and output a single minified faye.min.js that contains the whole lot, refactored so no additional serverside calls are necessary.
What happens is faye.min.js gets created, but it only contains the content of faye_browser.js, none of the other required files are included.
I have searched all over the web, and looked at a heap of different examples and none of them work for me.
What am I doing wrong here?
For anyone else trying to do this, I mist that on the download page it says:
The Node.js version is available through npm. This package contains a
copy of the browser client, which is served up by the Faye server when
running.
So to get it you have to pull down the code via NPM and then go into the NPM install dir and it is in the "client" dir...
Maybe I have fundamentally misunderstood how requirejs config works but I thought my configuration below made some libraries global so I could just use them in other files while only having to require and define files that I needed to use within the individual script. However I cannot reference $ (jQuery) in my application code without getting a reference error indicating it is not globally accessible. I've isolated the problem to the simple example below.
My file set up is as follows:
test
|
|-index.html
|-TestApp.js
|-MainApp.js
|-lib
| |-require.js
| |-jquery.js
| |-loadash.js
| |-backbone.js
|-css
|-test.css
The library file versions are RequireJS 2.1.22, jQuery 2.0.3, Loadash 3.10.1 and Backbone 1.2.1. I'm just trying to set up my environment and the approach I am taking is to pass my TestApp.js file to require.js to load the required files and bootstrap the application code in MainApp.js. The script in index.html is as follows:
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' type='text/css' href='css/test.css'/>
</head>
<body>
<div></div>
<script src="./lib/require.js" type="text/javascript" data-main="./TestApp.js"></script>
</body>
</html>
The referenced css script file simply ensured the div is visible as an orange square. See below:
div {
height: 100px;
width: 100px;
background-color: #FA6900;
border-radius: 5px;
}
It's the script line in index.html that then kicks off the application code by passing my configuration file to requirejs. This is the TestApp.js passed across as data-main. The TestApp.js is here:
require.config({
paths: {
'jquery': 'lib/jquery',
'lodash': 'lib/lodash',
'backbone': 'lib/backbone'
},
map: {
'*': {
// Backbone requires underscore. This forces requireJS to load lodash instead:
'underscore': 'lodash'
}
},
shim: {
jquery: {exports: '$'},
underscore: {
deps: ['jquery'],
exports: '_'
},
backbone: {
deps: ['underscore'],
exports: 'Backbone'
},
TestApp: {
deps: ['backbone'],
exports: 'TestApp'
}
}
});
require(['MainApp'], function(MainApp) {
MainApp.run();
});
The file above references the paths to the library files I want to use, I then remap loadash to be loaded when underscore is required (I need some of the extra loadash capability), I then use the shim to ensure the dependancies are correct as the files are loaded. Passing this config file to require.js in the index.html seems to be working as all of the files are showing as loaded in my browser. However the problem seems to be they do not appear to be globally accessible as I thought they would be.
Following the config section the last require call loads the MainApp.js file and calls the exposed run function. The MainApp.js looks like this:
define(function(require) {
var run = function() {
$(document).ready(function() {
$('div').click(function() {
$('div').fadeOut('slow');
});
});
};
return {
run: run
};
});
As far as I understood I should not need to require the files I already mentioned in the require config, I thought they should be loaded and available to this code. This is where I have misunderstood what is going on or have missed a step out. The exposed run function is being called but the first line that calls $ throws the error:
ReferenceError: Can't find variable: $
So my questions are:
What have I got wrong in my thinking?
(or) What am I doing incorrectly?
What should I be doing in order to preload and make available
frequently referenced libraries so that I do not need to require and
define them in every file I have?
As far as I understood I should not need to require the files I already mentioned in the require config, I thought they should be loaded and available to this code.
You misunderstood how RequireJS works. You should read the documentation from start to finish. For now, here are things you should change.
You should require jquery in your MainApp module:
define(function(require) {
var $ = require("jquery");
You should remove your shims that you have for jquery, underscore and backbone as they all call define and shim is only for code that does not call define. I don't know what TestApp is but if it is your own code, you really should make it into a proper AMD module and remove the shim.
#Louis has made me realise the error in what I was doing above. Changing the shim in TestApp.js so that is reads:
MainApp: {
deps: ['backbone'],
exports: 'MainApp'
}
Corrected the problem, now Backbone, $ and _ are all available to the rest of my application code without cluttering up each files require. i.e. I do not need to begin every file with:
define (['lib/jquery', 'lib/loadash', 'lib/backbone'], function($, _ , Backbone) {
Given in my actual app the list of common deps is quite large this means I only need to define locally used resources and can control the paths from a single location.
I am using Browserify to compile a large Node.js application into a single file (using options --bare and --ignore-missing [to avoid troubles with lib-cov in Express]). I have some code to dynamically load modules based on what is available in a directory:
var fs = require('fs'),
path = require('path');
fs.readdirSync(__dirname).forEach(function (file) {
if (file !== 'index.js' && fs.statSync(path.join(__dirname, file)).isFile()) {
module.exports[file.substring(0, file.length-3)] = require(path.join(__dirname, file));
}
});
I'm getting strange errors in my application where aribtrary text files are being loaded from the directory my compiled file is loaded in. I think it's because paths are no longer set correctly, and because Browserify won't be able to require() the correct files that are dynamically loaded like this.
Short of making a static index.js file, is there a preferred method of dynamically requiring a directory of modules that is out-of-the-box compatible with Browserify?
This plugin allows to require Glob patterns: require-globify
Then, with a little hack you can add all the files on compilation and not executing them:
// Hack to compile Glob files. Don´t call this function!
function ಠ_ಠ() {
require('views/**/*.js', { glob: true })
}
And, for example, you could require and execute a specific file when you need it :D
var homePage = require('views/'+currentView)
Browserify does not support dynamic requires - see GH issue 377.
The only method for dynamically requiring a directory I am aware of: a build step to list the directory files and write the "static" index.js file.
There's also the bulkify transform, as documented here:
https://github.com/chrisdavies/tech-thoughts/blob/master/browserify-include-directory.md
Basically, you can do this in your app.js or whatever:
var bulk = require('bulk-require');
// Require all of the scripts in the controllers directory
bulk(__dirname, ['controllers/**/*.js']);
And my gulpfile has something like this in it:
gulp.task('js', function () {
return gulp.src('./src/js/init.js')
.pipe(browserify({
transform: ['bulkify']
}))
.pipe(rename('app.js'))
.pipe(uglify())
.pipe(gulp.dest('./dest/js'));
});
I would like to split up my libs and my app code in separate bundles so I can insert script tags for each separately since I don't want jQuery, Backbone and Underscore to be added to each of my apps bundles.
However, I've tried several ways of doing this and each time I get an error from Backbone saying:
Uncaught TypeError: Cannot read property 'ajax' of undefined
I'm compiling a libs.js file that looks like this:
global.$ = require('./jquery')
global._ = require('underscore')
global.Backbone = require('backbone')
I had to manually download jQuery and stuff it in my /src/vendor folder because nom install jquery just fails for some reason.
I also have some simple test app code that compiles to app.js:
// User.js
var Backbone = require('backbone')
module.exports = User = Backbone.Model.extend({
url : '/user'
});
// app.js
var User = require('./user');
var u = new User()
u.on('change', function(e){
$('h1').append('Updated!')
});
u.fetch()
In my HTML the script tag for libs.js precedes that of app.js.
Maybe I've just approached this whole thing in a weird way from the start, because there doesn't seem to be much helpful in the way of googling when it comes to using these libs in this way, so any input on this is greatly appreciated!
I read up some more about externalizing, aliasing and shimming in Browserify. I was finally able to put together a Coffeescript gruntfile configuration that works:
browserify:
libs:
src: ['src/vendor/jquery.js', 'underscore', 'backbone'],
dest: 'public/js/libs.min.js'
options:
alias: ['backbone:', 'underscore:']
shim:
jQuery:
path: 'src/vendor/jquery'
exports: '$'
home:
src: ['src/js/main-home.js']
dest: 'public/js/main-home.min.js'
options:
external: ['backbone', 'underscore']
In main-home.js I am now able to do var Backbone = require('backbone') and then Backbone.$ = $ and everything works.
Seem like jQuery is not loaded correctly, that error is probably because you are attempting to call $.ajax but $ is undefined.
Maybe another reason maybe because that you're trying to load jQuery before Backbone. Try to do the opposite way by include your Backbone before jQuery instead.
Trying to create an AMD Javascript library to be included in non-AMD projects. Here's my setup:
app.coffee
define ->
class App
constructor: -> console.log 'instantiating App'
init: -> console.log 'Init called'
index.html
<body>
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="dev-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){
console.log('doc', window.app);
});
$(function(){
console.log('func', window.app);
});
window.onload = function()
{
console.log('onload', window.app);
}
</script></body>
main.js
require(['cs!app'], function(app){
return window.app = new app;
});
I am building this project with r.js optimizer to get dev-latest.js as the output. Here's my build file (PS: Build is successful):
({
baseUrl: './vendor',
paths: {
app: '../app',
'require-lib': 'require'
},
name: '../main',
out: 'dev-latest.js',
include: 'require-lib',
preserveLicenseComments: false
})
When running the code in the browser here's the output:
doc undefined
func undefined
onload undefined
instantiating App dev-latest.js:1
app.init(); // running this manually in the browser console
Init called
How should I go about this and get app to load before being used ?
Using AMD you cant rely on a module being created outside of a module. The only reliable way is to load the result of a module into another module. So in your case need to create a new module which then can lsiten to $.read:
define( [App], (App)->
$(document).ready(function(){
console.log('doc', App);
});
)
Solved it by using browserify (just found about it) which uses the CommonJS form of dependency loading and saves all that clutter. Also a great template for starting projects is amitayd's grunt-browserify-jasmine setup