StealJS page
StealJS is a collection of command line and JavaScript client utilitiesthat make building, packaging, and sharing JavaScript applications easy.
Features
Behold StealJS's goodies:
Dependency Management (steal)
steal loadsJS and other file into your app. Features:
- Loads JavaScript, CSS, Less, CoffeeScript, and a variety of client-side templates.
- Can be use with scripts that don't use steal.
steal('widgets/tabs.js', './style.css', function(){$('#tabs ).tabs();
});
JS/CSS Concatenation and Compression (steal.build)
The steal.buildplugin combines an application's files into a single minified JavaScript andCSS file extremely easy. Features:
- Configurable compressors (defaults to Google Closure).
- Compresses Less and CoffeeScript.
- Pre-processes and compresses client-side templates (templates don't have to be parsed).
js steal/buildjs mypage.html
Logging (steal.dev)
steal.devlogs messages cross browser. Messages are removed in production builds.
steal.dev.log('something is happening');
Code Generators (steal.generate)
steal.generatemakes building code generators extremely easy. Features:
- Pre-packaged JMVC style code generators.
- Easily author custom generators.
js jquery/generate/app cookbook
Package Management (steal.get)
steal.getis a simple JavaScript version of ruby gemsfeaturing:
- Download and install plugins from remote SVN or GIT repositories.
- Installs dependencies.
js steal/getjs http://github.com/jupiterjs/mxui/
Code Cleaner (steal.clean)
steal.cleancleans your code and checks it against JSLint.
js steal/clean path/to/page.html
Searchable Ajax Apps (steal.html)
steal.htmlmakes Google-crawlable html from your ajax app.
js steal/htmljs http://localhost/cookbook.html#recipes
steal class
steal is a function that loads scripts, css, and other resources intoyour application.
steal(FILE_or_FUNCTION, ...)
Quick Walkthrough
Add a script tag that loads steal/steal.js
andadd the path to the first file to load in the query string like:
<script type='text/javascript' src='../steal/steal.js?myapp/myapp.js'></script>
Then, start loading things and using them like:
steal(
'myapp/tabs.js',
'myapp/slider.js'
,
'myapp/style.css'
,
function(){
// tabs and slider have loaded
$(
'#tabs').tabs();
$(
'#slider').slider()
})
Make sure your widgets load their dependencies too:
// myapp/tabs.js
steal(
'jquery',
function(){
$.fn.tabs =
function(){
...
}
})
Examples:
// Loads ROOT/jquery/controller/controller.js
steal(
'jquery/controller')
steal(
'jquery/controller/controller.js')
// Loads coffee script type and a coffee file relative to
// the current file
steal(
'steal/coffee').then(
'./mycoffee.coffee')
// Load 2 files and dependencies in parallel and
// callback when both have completed
steal(
'jquery/controller',
'jquery/model',
function(){
// $.Controller and $.Model are available
})
// Loads a coffee script with a non-standard extension (cf)
// relative to the current page and instructs the build
// system to not package it (but it will still be loaded).
steal({
src:
"./foo.cf",
packaged:
false,
type:
"coffee"
})
The following is a longer walkthrough of how to install anduse steal:
Adding steal to a page
After installing StealJS (or JavaScriptMVC), find the steal
folder with steal/steal.js
.
To use steal, add a script tag to steal/steal.js
to your html pages.
This walkthrough assumes you have the steal script in public/steal/steal.js
and a directory structure like:
/public
/steal
/pages
myapp.html
/myapp
myapp.js
jquery.js
jquery.ui.tabs.js
To use steal in public/pages/myapp.html
, add ascript tag in myapp.html
:
<script type='text/javascript'
src='../steal/steal.js'>
</script>
PRO TIP: Bottom load your scripts. It willincrease your application's percieved response time.
Loading the First Script
Once steal has been added to your page, it's time to loadscripts. We want to load myapp.js
and have it load jquery.js
and jquery.ui.tabs.js
.
By default, steal likes your scripts to be within in the steal.rootfolder. The steal.rootthe folder contains the steal
folder. In this example, it is the public
folder.
To load myapp/myapp.js
, we have two options:
Add a script tag
Add a script tag after the steal script that 'steals' myapp.js
like:
<script type='text/javascript'>
steal('myapp/myapp.js')
</script>
Add the script parameter
The most common (and shortest) way to load myapp.js
is to add the script path to the steal script's src after in the query params.So, instead of adding a script, we change the steal script from:
<script type='text/javascript'
src='../steal/steal.js'>
</script>
To
<script type='text/javascript'
src='../steal/steal.js?myapp/myapp.js'>
</script>
PRO TIP: You can also just add ?myapp
tothe query string.
Loading Scripts
We want to load jquery.js
and jquery.ui.tabs.js
into the page and then add then create a tabs widget. First we need to load jquery.js
.
By default, steal loads script relative to steal.root.To load myapp/jquery.js
we can the following to myapp.js
:
steal(
'myapp/jquery.js');
But, we can also load relative to myapp.js
like:
steal(
'./jquery.js');
Next, we need to load jquery.ui.tabs.js
. Youmight expect something like:
steal(
'./jquery.js',
'./jquery.ui.tabs.js')
to work. But there are two problems / complications:
- steal loads scripts in parallel and runs out of order
jquery.ui.tabs.js
depends on jQuery being loaded
This means that steal might load jquery.ui.tabs.js
before jquery.js
. But this is easily fixed.
steal.static.thenwaits until all previous scripts have loaded and run before loading scriptsafter it. We can load jquery.ui.tabs.js
after jquery.js
like:
steal(
'./jquery.js').then(
'./jquery.ui.tabs.js')
Finally, we need to add tabs to the page after the tabs'swidget has loaded. We can add a callback function to steal that will get calledwhen all previous scripts have finished loading:
steal(
'./jquery.js').then(
'./jquery.ui.tabs.js',
function($){
$(
'#tabs').tabs();
})
Other Info
Exclude Code Blocks From Production
To exclude code blocks from being included in productionbuilds, add the following around the code blocks.
//!steal-remove-start
code to be removed at build
//!steal-remove-end
Lookup Paths
By default steal loads resources relative to steal.root.For example, the following loads foo.js in steal.root
:
steal(
'foo.js');
// loads //foo.js
This is the same as writing:
steal(
'//foo.js');
Steal uses '//'
to designate the steal.rootfolder.
To load relative to the current file, add "./"
or "../"
:
steal(
"./bar.js",
"../folder/zed.js");
Often, scripts can be found in a folder within the samename. For example, $.Controlleris in //jquery/controller/controller.js
. For convience, if stealis provided a path without an extension like:
steal(
'FOLDER/PLUGIN');
It is the same as writing:
steal(
'FOLDER/PLUGIN/PLUGIN.js')
This means that //jquery/controller/controller.js
can be loaded like:
steal(
'jquery/controller')
Types
steal can load resources other than JavaScript.
Constructor
Loads resources specified by each argument. By default,resources are loaded in parallel and run in any order.
new steal(resource...) -> steal
{String|Function|Object}
Each argument specifies a resource. Resources can be givenas a:
Object
An object that specifies the loading and build behavior ofa resource.
steal({
src:
"myfile.cf",
type:
"coffee",
packaged:
true,
unique:
true,
ignore:
false,
waits:
false
})
The available options are:
· src {String} - the pathto the resource.
· waits {Boolean default=false}- true the resource should wait for prior steals to load and run. False if theresource should load and run in parallel. This defaults to true for functions.
· unique {Boolean default=true}- true if this is a unique resource that 'owns' this url. This is true forfiles, false for functions.
· ignore {Boolean default=false}- true if this resource should not be built into a production file and notloaded in production. This is great for script that should only be available indevelopment mode.
· packaged {Boolean default=true}- true if the script should be built into the production file. false if thescript should not be built into the production file, but still loaded. This isuseful for loading 'packages'.
· type {String default="js"}- the type of the resource. This is typically inferred from the src.
String
Specifies src of the resource. For example:
steal(
'./file.js')
Is the same as calling:
steal({src:
'./file.js'})
Function
A callback function that runs when all previous steals havecompleted.
steal(
'jquery',
'foo',
function(){
// jquery and foo have finished loading
// and runing
})
{steal}
the steal object for chaining
steal.static.bind function
Listens to events on Steal
API
steal.bind(event, listener) ->undefined
event {String}
listener {Function}
returns {undefined}
steal.static.cur function
Gets the currently running script location.
API
steal.cur(file) -> undefined
file {}
steal.static.LOAD attribute
var name = function(stel){ if(stel.options && stel.options.type =="fn"){ return stel.options.orig.toString().substr(0,50) } returnstel.options ? stel.options.rootSrc : "CONTAINER" }
steal.p.load =before(steal.p.load, function(){
console.log("load", name(this), this.loading, this.id)
})
steal.p.loaded =before(steal.p.loaded, function(){
console.log("loaded", name(this), this.id)
})
steal.p.complete =before(steal.p.complete, function(){
console.log("complete", name(this), this.id)
})
steal.static.map function
Maps a 'rooted' folder to another location.
API
steal.map(from, to) -> steal
from {String|Object}
the location you want to map from. For example: 'foo/bar'
to {optional:String}
where you want to map this folder too. Ex: 'http://foo.cdn/bar'
returns {steal}
steal.static.options attribute
Configurable options
steal.static.pageUrl function
Gets or sets the location of the page using steal. This defaults to thewindow's location.
However, sometimes it is necessary to have steal believe it is makingrequests from another page.
API
steal.pageUrl(newPage) ->steal.File
newPage {optional:String}
a path to the page using steal (probably the windows location)
returns {steal.File}
returns the last path to a page passed to pageUrl, converted to asteal.File object
steal.static.request function
Performs an XHR request
API
steal.request(options, success,error) -> undefined
options {Object}
success {Function}
error {Function}
returns {undefined}
steal.static.require function
Called for every file that is loaded. It sets up a string of methodscalled for each type in the conversion chain and calls each type one by one.
For example, if the file is a coffeescript file, here's what happens:
- The "text" type converter is called first. This will perform an AJAX request for the file and save it in options.text.
- Then the coffee type converter is called (the user provided method). This converts the text from coffeescript to JavaScript.
- Finally the "js" type converter is called, which inserts the JavaScript in the page as a script tag that is executed.
API
steal.require(options, success,error) -> undefined
options {Object}
the steal options for this file, including path information
success {Function}
a method to call when the file is converted and processed successfully
error {Function}
a method called if the conversion fails or the file doesn't exist
returns {undefined}
steal.static.root attribute
The location of the steal folder.
steal.static.rootUrl function
Gets or sets the path from the current page to steal's (orJavaScriptMVC's) root folder. When passed a src, it sets the root folder.Otherwise, it returns the path to the root folder.
This is the path from which all plugins are stolen. When you steal aplugin like steal("jquery/controller"), the plugin path is joinedwith this rootUrl to create a full path to the controller.js file.
By default, the rootUrl is calculated from the steal script and the windowlocation. For example, if the script tag looks like this:
<script type='text/javascript' src='../../steal/steal.js?ui/app'></script>
rootUrl will be set to "../../". Setting the rootUrl can beuseful if you want to have steal.js in a different location.
Example
The following sets steal root to a different folder.
steal.rootUrl("../../jmvc/")
This appends "../../jmvc" to paths loaded from steal.static.root.In some strange cases this might be desirable if plugin folders are in adifferent location from the steal directory.
It also sets the current url to this directory so the first calls to stealwork relative to the root JMVC directory.
API
steal.rootUrl(src) -> String
src {optional:String}
a relative path from the current page to the root directory of JMVC, like../../
returns {String}
returns the last path passed to rootUrl
steal.static.then function
Calls steal, but waits until all previous steals have completed loadinguntil loading the files passed to the arguments.
API
steal.then() -> undefined
returns {undefined}
steal.static.type function
Registers a type. You define the type of the file, the basic type itconverts to, and a conversion function where you convert the original file toJS or CSS. This is modeled after the AJAX converters injQuery.
Types are designed to make it simple to switch between steal's developmentand production modes. In development mode, the types are converted in thebrowser to allow devs to see changes as they work. When the app is built, theseconverter functions are run by the build process, and the processed text isinserted into the production script, optimized for performance.
Here's an example converting files of type .foo to JavaScript. Foo is afake language that saves global variables defined like. A .foo file might looklike this:
REQUIRED FOO
To define this type, you'd call steal.type like this:
steal.type("foo js", function(options,original, success, error){
var parts = options.text.split(" ")
options.text = parts[0]+"='"+parts[1]+"'";
success();
});
The method we provide is called with the text of .foo files inoptions.text. We parse the file, create JavaScript and put it in options.text.Couldn't be simpler.
Here's an example, converting coffeescript toJavaScript:
steal.type("coffee js", function(options,original, success, error){
options.text = CoffeeScript.compile(options.text);
success();
});
In this example, any time steal encounters a file with extension .coffee,it will call the given converter method. CoffeeScript.compile takes the text ofthe file, converts it from coffeescript to javascript, and saves the JavaScripttext in options.text.
Similarly, languages on top of CSS, like LESS,can be converted to CSS:
steal.type("less css", function(options,original, success, error){
new (less.Parser)({
optimization: less.optimization,
paths: []
}).parse(options.text, function (e, root){
options.text = root.toCSS();
success();
});
});
This simple type system could be used to convert any file type to be usedin your JavaScript app. For example, ymlcould be used for configuration. jQueryMX uses steal.type to support JStemplates, such as EJS, TMPL, and others.
API
steal.type(type, cb( options,original, success, error )) -> undefined
type {String}
A string that defines the new type being defined and the type beingconverted to, separated by a space, like "coffee js".
There can be more than two steps used in conversion, such as "ejsview js". This will define a method that converts .ejs files to .viewfiles. There should be another converter for "view js" that makesthis final conversion to JS.
cb( options, original, success, error ) {Function}
a callback function that converts the new file type to a basic type. Thismethod needs to do two things: 1) save the text of the converted file inoptions.text and 2) call success() when the conversion is done (it can workasynchronously).
- options - the steal options for this file, including path information
- original - the original argument passed to steal, which might be a path or a function
- success - a method to call when the file is converted and processed successfully
- error - a method called if the conversion fails or the file doesn't exist
returns {undefined}
CoffeeScript page
plugin: steal/coffee
Requires a CoffeeScriptscript.
CoffeeScript is a more 'refined' version of JavaScript that lets you writecode like:
number = -42 if opposite
CoffeeScript is normally used on the server, but steallets you load CoffeeScripts in the browser, and compress their JavaScriptoutput into your production builds.
Use
First, create a coffee script like:
console.log "There are no () around this string!"
Save this in a file named log.coffee.
Next, you have to require the steal/coffee plugin andthen use steal.coffee to load your coffee script:
steal('steal/coffee').then(function(){
steal.coffee('log');
});
Loads CoffeeScript files relative to the current file. It's expected thatall CoffeeScript files end with coffee.
Less page
plugin: steal/less
Lets you build and compile Less cssstyles.
Less is an extension of CSS that adds variables, mixins, and quite a bitmore. You can write css like:
@brand_color: #4D926F;
#header {
color: @brand_color;
}
h2 {
color: @brand_color;
}
Use
First, create a less file like:
@my_color red
body { color: @my_color; }
Save this in a file named red.less.
Next, steal the steal/less plugin, wait for it to finishloading (by using then)and then load the less file:
steal('steal/less').then('./red.less');
Loads Less files relative to the current file. It's expected that all Lessfiles end with less.
steal.static.unbind function
Unbinds an event listener on steal
API
steal.unbind(event, listener)-> undefined
event {Object}
listener {Object}
returns {undefined}