Full Stack JavaScript Engineering
This is Code Fellows' textbook for The Full-Stack JavaScript Development Accelerator.
It's a GitBook project. Read Online
This book's latest published form is available at Full Stack JavaScript Engineering. Installation
npm -g install gitbook git clone https://github.com/codefellows/Full-Stack-JavaScript-Engineering.git Usage
Browse locally:
cd Full-Stack-JavaScript-Engineering gitbook serve .
Publishing
Bgitbook build . --output=publicuild the Gitbook and check in the changes to the public folder
gitbook build . --output=public git add public git commit git push heroku master # must be a contributor Contributing
Send us a pull request here on Github.
More info, see the GitBook README Pre-work
These pre-work tasks are optional, but recommended if you have any knowledge gaps. They are here to make sure you have a good foundational knowledge of JavaScript, jQuery, Git, and HTML/CSS Code School
We love CodeSchool.com's interactive courses. They are a great way to level up before the Development Acellorator.
Try jQuery
JavaScript Road Trip, Parts 1 and 2
These cover the basics of JavaScript, you may already know this stuff, especially if you did a JavaScript Code Fellows foundations course. It's o.k. Skip to JS Road Trip part 3 if you already have a good foundation.
Try Git Discover Chrome DevTools Crockford on JS Lecture Series
Watch the first Crockford on JS and any other lectures in the series. The whole series is 8+ hours long, so this will be something that will take some time. Asana
We use the Asana project management / TODO list system to keep track of assignments in class. Watch the Intro Video and any other videos or help documents necessary there.
The only thing that's different about the way we use Asana is that an instructor will check off when you are done with an assignment. You can always comment "DONE" if you need us to review the work. Required State Paperwork
Code Fellows LLC is licensed as a technical training school by the State of Washington and we follow all state laws and regulations. All students are required to fill out two important forms:
1: the demographic survey, and 2: Acknowledge receipt of the course catalog and honor code.
Please print out these forms, fill them out and sign them, and bring them to the first class meeting. Connect to IRC
Internet Relay Chat (IRC) despite being an ancient chat protocol, is highly used in the JavaScript, Node.js, and general web development community. It's important that you're familiar with it and can utilize it for help and to connect with others in the community. We have our own channel to model this community. The channel has two "bots", a logging bot written in Ruby, and a fun bot called "codehue" written in NodeJS.
Connect to the class IRC channel #codefellows on freenode.net and say hello. If you want to be able to talk on the ##javascript channel, you need to register a nickname with Freenode. Type /msg NickServ help to get started from your IRC client. Mac, best free client is LimeChat. Unix, your package manager should have XChat or Pidgin. http://www.irchelp.org/ is a great intro site if you're new to IRC. A short article on irc etiquette: http://geoff.greer.fm/2012/05/19/programmer-irc-etiquette/ Also see https://speakerdeck.com/ivanoats/a-good-question
There is no submission for this assignment. We'll see you on the #codefellows channel in class, and on Gitter.IM. They are very useful for sending links to everyone during class, asking questions in the evening, or just socializing.
We also use Gitter.IM as a chatroom just for our class. Click on this button to join. Day One
Computer Setup Questions verify node and npm version Icebreaker.js Core Protocols (Keynote) Go over JS tools mind map Pull Request Workshop
Asana overview and mention want ads assignment
don't check off things add your name as a subtask, use that URL of the subtask Github integration where is your API key? commit message format
Show video and Talk about Agile, intro Along-the-Way project, and share task in Asana
Check in on IRC / Gitter.IM Demo Grunt and File Redirection A List of Foundational JavaScript Tools by Kalina Wu, Ivan Storck, and Sarah Fischer
In our development accelerator, students are introduced to several tools and libraries to expand the abilities of their code. Kalina, one of our former JavaScript students, compiled a list of these tools and wanted to share it with other Code Fellows.
Ivan Storck, our JavaScript Development Accelerator instructor, used Kalina's list to draft up this helpful mind map: General
Scaffolding Tools (for starting projects)
Yeoman - Yeoman is a robust and opinionated client-side stack, comprising tools and frameworks that can help developers quickly build beautiful web applications.
Build Tools (automation)
Grunt.js - The Grunt ecosystem is huge and it's growing every day. With literally hundreds of plugins to choose from, you can use Grunt to automate just about anything with a minimum of effort. Pint.js (Grunt helper) - Pint is a small, asynchronous, dependency-aware wrapper around Grunt, attempting to solve some of the problems that accompany a build process at scale. Gulp.js - Gulp's use of streams and code-over-configuration makes for a simpler and more intuitive build. Browserify.js (for browser) - Browserify is a development tool that allows us to write node.js-style modules that compile for use in the browser. Just like node, we write our modules in separate files, exporting external methods and properties using the module.exports and exports variables. Uglify.js - Uglify.js is a JavaScript parser / mangler / compressor / beautifier library for NodeJS.
Package Management Tools
Homebrew (Mac OS) - Homebrew installs the stuff you need that Apple didn't. Apt (Ubuntu) - The apt-get command is a powerful command-line tool, which works with Ubuntu's Advanced Packaging Tool (APT) performing such functions as installation of new software packages, upgrade of existing software packages, updating of the package list index, and even upgrading the entire Ubuntu system. NPM - npm is the official package manager for Node.js. Bower - Bower is a package manager for the web. Front End
MVC Frameworks
Backbone.js - Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, and views with declarative event handling. It connects it all to your existing API over a RESTful JSON interface. Ember.js - Ember makes Handlebars templates even better by ensuring your HTML stays up-to-date when the underlying model changes. To get started, you don't even need to write any JavaScript. Angular.js - AngularJS lets you extend HTML vocabulary for your application. The resulting environment is extraordinarily expressive, readable, and quick to develop.
Templates
Handlebars.js - Handlebars provides the power necessary to let you build semantic templates effectively with no frustration. Mustache templates are compatible with Handlebars, so you can take a Mustache template, import it into Handlebars, and start taking advantage of the extra Handlebars features. Mustache.js (less built-out than Handlebars) - Mustache is a simple web template system with implementations available for ActionScript, C++, Clojure, CoffeeScript, ColdFusion, D, Erlang, Fantom, Go, Java, JavaScript, Lua, .NET, Objective-C, Pharo, Perl, PHP, Python, Ruby, Scala and XQuery. Jade - Jade is a node template engine designed primarily for server-side templating in node.js. Haml-js - Haml-js allows the Haml syntax to be used in a JavaScript project. It has most of the same functionality as the original Haml. Eco - Eco lets you embed CoffeeScript logic in your markup.
Testing
Casper.js - CasperJS is a navigation scripting and testing utility for PhantomJS and SlimerJS written in Javascript. Zombie.js - Zombie.js is a lightweight framework for testing client-side JavaScript code in a simulated environment. No browser required. Back End
Servers
Express - Express is a web application framework for Node. Node - Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications.
Databases
MongoDB - MongoDB is an open-source document database, and the leading NoSQL database. Postgresql - PostgreSQL is a powerful, open source, object-relational database system. SQL - SQL is used to communicate with a database. According to the American National Standards Institute, it is the standard language for relational database management systems.
Architectural Style
RESTful - Representational State Transfer is an architectural style consisting of a coordinated set of architectural constraints applied to components, connectors, and data elements, within a distributed hypermedia system.
Testing
Cucumber.js - Cucumber.js takes the popular behavior-driven development tool and applies it to your JavaScript stack. Jasmine - Jasmine is a behavior-driven development testing framework for JavaScript. It does not rely on browsers, DOM, or any JavaScript framework. Thus it's suited for websites, Node.js projects, or anywhere that JavaScript can run. Mocha - Mocha is a feature-rich JavaScript test framework running on node.js and the browser, making asynchronous testing simple and fun. Q-Unit - Q-Unit is a powerful, easy-to-use JavaScript unit testing framework. It's used by the jQuery, jQuery UI and jQuery Mobile projects and is capable of testing any generic JavaScript code.
Assertion Libraries
Chai - Chai is a BDD / TDD assertion library for node and the browser that can be delightfully paired with any javascript testing framework.
Functional Programming Tools
Underscore.js - Underscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects. Lo-Dash - Lo-Dash is a utility library delivering consistency, customization, and performance.
Update:
Have a tool you think should be on the list? Check out this article and the associated MindNode mind map (OPML) on Github. Submit a pull request and send us your suggestions to add new and popular tools! Pull Request Practice
Create a folder with your name in the class repository.
Send a Pull Request to the class repo, with your own folder.
Inside your folder should be a single readme.md file that contains some basic info about you. You should include your GitHub username, linked to your GitHub profile. Also link to your Twitter account, your LinkedIn page, and any other relevant information or online presence you'd like to share with your classmates.
I have created an example folder for myself. Computer Setup
Set up your computer with the following tools:
Latest version of Ruby (for Sass, and other tools) Node.js, MongoDB, Redis
Editors: We use Atom.io or Sublime Text 3 in class, and I'm betting you already do too (unless you rock Vim or Emacs). Sublime Text has a fully-featured, unlimited time Trial mode.
Optional: if you are coming from an IDE like Visual Studio or Eclipse, you may like WebStorm (trial version) better than Sublime Text because of the autocompletion and debugging tools. It's also cheaper for an academic license (79)
And if you're a strict proponent of open source, or want to dogwood and customize your editor in JavaScript, there are two great free editors: Brackets and Light Table.
Sign up for these free web services:
GitHub (you may have this already but there is also https://education.github.com/discount_requests/new try it while you're here)
Mac OS:
Homebrew http://brew.sh Note: the instructions are at the end of the web page.
rbenv, ruby-build, ruby 2.1.1 and the sass gem
brew doctor brew update brew install rbenv ruby-build rbenv-gem-rehash echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bash_profile echo 'eval "$(rbenv init -)"' >> ~/.bash_profile rbenv install 2.1.1 rbenv global 2.1.1 gem install sass NOT use sudo to install ruby or gems if you get a permissions error when installing sass, somehow system ruby is still active. Try restarting your terminal, or if it persists, check for the items above in your .bash_profile file
Node.js
brew install nvm nvm install 0.10 nvm alias default 0.10 add source $(brew --prefix nvm)/nvm.sh to your .bash_profile or .zshrc Install some commonly used packages with npm: npm -g install grunt- cli jshint Reference the NVM README if you get stuck
Totally Optional, but you may want a relational database. Only do this if you have time. I Totally Optional, but you may want a relational database. Only do this if you have time. I choose PostgreSQL:
Follow Ivan's blog post: https://www.codefellows.org/blogs/how-to-install- postgresql
Pick a programmer's editor:
Try out http://atom.io and ask around for an invite. or go with the crowd and choose Sublime Text 3: http://www.sublimetext.com/3 Package Control: https://sublime.wbond.net/installation Or, try Adobe's open source http://brackets.io Which one to choose? I like Atom.io and Brackets because you can customize them with JavaScript. Customizing Sublime requires knowledge of Python.
MongoDB
brew install mongodb Follow the directions that homebrew tells you. You can always do brew info mongo you can start mongo with brew services start mongo you can stop redis with brew services stop redis
Redis
brew install redis Follow the directions that homebrew tells you. You can always do brew info redis you can start redis with brew services start redis you can stop redis with brew services stop redis
Heroku Toolbelt
brew install heroku-toolbelt
Ubuntu:
No need for homebrew you already have a perfectly good package management system. In your terminal preferences make sure that "Run Command as a login shell is an enabled profile preferences" check these two screenshots: http://cl.ly/image/220M3f093v2M http://cl.ly/image/3i2O0y0A3e04 rbenv, ruby-build, and ruby: https://www.digitalocean.com/community/articles/how-to- install-ruby-on-rails-on-ubuntu-12-04-lts-with-rbenv--2 NOTE you DO NOT have to buy a digital ocean server, this is instructions for how to install LOCALLY. Ignore the create a server droplet step NOTE replace 1.9.3 with the latest version of ruby: 2.1.1 Another alternative way to install rbenv: https://github.com/sstephenson/rbenv#basic-github-checkout gem install sass // DO NOT use sudo to install gems node.js: compile node from source, following the directions here. Install Grunt-CLI (command line interface) npm -g install grunt-cli PostgreSQL (again, totally optional and only do if you have time) Follow Ivan's blog post: https://www.codefellows.org/blogs/how-to-install- postgresql no need to install the pg gem - you won't be connecting to Postgres from ruby here. Sublime Text 3 http://docs.sublimetext.info/en/latest/getting_started/install.html MongoDB - https://www.digitalocean.com/community/articles/how-to-install-mongodb- on-ubuntu-12-04 NOTE you DO NOT have to buy a digital ocean server, this is instructions for how to install LOCALLY. Ignore the create a server droplet step Redis - https://library.linode.com/databases/redis/ubuntu-12.04-precise-pangolin same as above Heroku Toolbelt - sudo apt-get install heroku-toolbelt Test Out Grunt
By testing to see if grunt works on a project we can see if you have done most of the setup tasks needed.
Let's just make sure your computer is set up with node and npm and can run tests.
1. Clone this Github project. 2. Run the tests, and redirect the output to a text file. the packages we need are Install the npm modules need with npm install 3. Create a subtask with your name 4. Comment on your subtask, with a link to a text file posted on gist.github.com Installing Node from Source
This is only if you need to, generally just on Linux systems.
Goto the node website Click download Click the source download
Go to the directory where you downloaded the source and do:
tar -xzvf
add the following to your shell startup scripts (.bash_profile, .bashrc or .profile)
export PATH=$PATH:$HOME/.node/bin export NODE_PATH=$HOME/.node/lib/node_modules Making sure it works
Restart your shell and the command node -v should print out the current node version. You should now be able to install Node packages globally without sudo. Try npm -g install jshint. If that works, without any EACCESS errors, you're good! Day Two
Class Structure Instructor Availability in the Mornings Open Questions Demo: Making a branch and pull request to your own repo Node Slides Node Beginner Book NodeSchool.io Async Demo the Node REPL
Use the node REPL - Read, Evaluate, Print Loop Simply type node from the command line. Process.nextTick
var truth_value = false; process.nextTick(function() { console.log(truth_value) }); truth_value = true;
What will the output be? False or True?
The answer is that the output will be true. Why? You might have thought it would be false, right? It's like the statements are having out of order.
It's because we are placing our function with conosole.log on the event queue. Hello Express
Express is a minimalistic web framework built on top of Node.js. Based on Ruby's Sinatra framework it abstracts away a lot of the boiler plate code required to get a Node web server up and running. Created by TJ Holowaychuck Express is built using Connect another abstraction for creating web servers with Node. Express 3.x includes a suite of middleware that were abstracted into their own modules with Express 4. Read more about it here
The first step in creating an express application from scratch is to create a new folder with mkdir hello_express. Change into the director with cd hello_express and create a file with the name package.json. Inside of the file place the following:
{ "name" : "hello-express", "description" : "a hello world web application written in express", "version" : "0.0.1", "dependencies" : { "express" : "^4.0" } }
A package.json file is found in nearly every Node packag or application. It tells npm about our application. The name and description would appear in npm if we were creatin a node package. The version is the Semantic Versioning version of our application and the dependencies tell npm what packages we need in order to run our application. In this case the only package that we need is express. After saving this file run npm install from the command in our hello_express directory and npm will install Express and all of it's dependencies and save them into a folder called node_modules. Now seems like a perfect time to create a git repository for our application.
git init touch .gitignore echo "node_modules/" >> .gitignore git add . git commit -m "add package.json and .gitignore"
First we need to create a .gitignore file. This file tells git not include our node_modules folder in our version control. This folder can get quite large and we already have our dependencies declared in our package.json file, so it becomes redundant. Now we need to create a simple web server. Create a file called server.js and add the following code:
var express = require('express'); var http = require('http');
var app = express();
app.get('/', function(req, res){ res.send('hello world!'); });
var server = http.createServer(app); server.listen(3000, function(){ console.log('the server is running on port 3000'); });
In this file we first require the express package within our server.js file. We then require http which will be used to create the actual server. Then we create our app by calling the root express function. The app.get line is a REST get request to our root url that simple writes 'hello world!' to the browser. In the final section we create a server and start it listening on port 3000, we pass a callback that gets called when the server is running that simple outputs 'the server is running on port 3000' to the console. To start our server simply run node server.js from the command line. Then point your preferred browser to http://localhost:3000, you should see the text hello world!.
Now this particular server isn't especially useful or interesting but we can modify it to serve static html pages using one of the few optional middlewares that didn't get abstracted out of Express 4, static. Modify your server.js file to look like this:
var express = require('express'); var http = require('http');
var app = express();
app.use(express.static(__dirname + '/public'));
var server = http.createServer(app); server.listen(3000, function() { console.log('the server is listening on port 3000'); });
Our server now serves any file located in the /public directory. The __dirname in this version of the server.js points to the root directory of our application. This is a node global and is available anywhere in a node program. Next we need to create the /public directory, run mkdir public from the console. Now place create an index.html file in the public directory and add the following to it:
If you close the server we had running and run node server.js again, when you browse to http://localhost:3000 you should see the text Hello World from an html document. You can also serve up anything you place in the public directory, including javascript files, images, css stylesheets and other html files. Don't forget to commit the changes! git add . git commit -m "serving static files" Day Three
On day three, we will cover:
Responsive Web Design Grunt Yeoman 28% of website traffic comes from mobile. Are you prepared? by Elliot Chong and Sarah Fischer
It happens to the best of us.
You're standing in a store, product in front of you, and you wonder what users are saying about it. You pull out your smartphone and do a quick search for the brand.
The site has great functionality and engaging features — for a desktop. You try to check tiny boxes and navigate little menus on your 3-inch screen, cursing your thumbs for not being more nimble and promising yourself that any site you build will be responsive for smartphones.
There is a linear relationship between the number of smartphone users and the need for responsive websites. But creating a website or application that looks good and works well on a desktop, tablet, and smartphone is tricky. Think the solution is to simply create two separate sites with optimized CSS for mobile and desktop users? Think again.
3 problems with using different code bases for different devices
Problem #1: User-Agent Redirects
User-agent redirects detect the user's device and redirects from a desktop URL to one that displays and functions correctly on a mobile device, usually a subdomain at m.example.com.
Problem #2: Two Code Bases
Two. Code. Bases. Assuming that isn't enough reason right there to abandon this duplicate-site notion, consider the additional work and coordination to update both codes.
Problem #3: URL Sharing Between Devices
A user is so impressed with your site or product that they share it on their social network from their phone. Sweet!
But half of their connections click the link and view it on a desktop, and the URL leads them to the mobile version of the site, which ends up looking narrow and broken on their 17-inch MacBook Pro. They're left unimpressed (and even a little put-off) and you're left with potential customers thinking your site isn't user-friendly.
Damn.
What about tablets?
Tablets (and the awkward middle-ground phablets — pick a side, already!) bring yet another size and user experience to consider. Some tablets come with cases that have built-in keyboards, which means they can function like a laptop. But users still want the option to use the touch screen and don't bother with keyboard add-ons.
What's a developer to do? Responsive Web Design
Responsive Web Design (RWD) conditionally modifies the layout of a webpage depending on the width of the device it's being viewed on.
Simple.
Mozilla's resource for web developers puts it oh so nicely:
Media queries, added in deprecated CSS3, let the presentation of content be tailored to a specific range of output devices without having to change the content itself.
In other words, you modify the CSS based on the browser's:
Width / Height
Orientation
Media Type (Screen, TV, Braille, etc.)
Color
Resolution
Aspect-Ratio
Our website is responsive — resizing the browser changes the layout of the text and images.
Using RWD on your website
Applying a grid layout to your website allows it to easily transition from phone to tablet to desktop displays, depending on the user's device. Mobile-tuned JavaScript enhances the user’s experience. Touch-optimized menus, for example, are beautifully simple and easy to use on a smartphone when implemented correctly.
Smart responsive web design is like the stage crew at a theater production — everything is going right when you don't notice it at all. So you want to build a responsive website
Where do you go from here? There are some options for transitioning your website to a responsive layout, if you're ambitious and want to get started with RWD:
1. Foundation This open source product by Zurb is a responsive front-end framework that offers several different HTML templates to choose from. 2. Skeleton This boilerplate for developing mobile-friendly websites gives you a foundation for your website. The bonus for Skeleton is its simple syntax and basic provision of basic styles, which means the look of your site is entirely up to you. 3. HTML and CSS: design and build websites by Jon Duckett If you want to skip the templates and create your own responsive website from scratch, Ch. 15: Layouts offers great instruction on grid layouts. This is also a great place to go if you're just getting started in web development. 4. Beginner's Guide to Grids with Zurb Foundation 5 Try it out—Your mobile visitors will sing your praises (or just appreciate how easy your website is to use on a smartphone. Win-win!). Grunt
Review the slides below: Personal Blog Site Tutorial with Yeoman and Zurb Example Blog Layout and Tutorial
This is a simple blog made as teaching example. Made with:
Yeoman generator-browserify Zurb Foundation Blog Template Other Technologies Used
Grunt NPM Sass (SCSS) SVG (Headshot image of me) svgo (npm install -g svgo) Tutorial
Prerequisites
Node and NPM installed. I recommend brew install nvm on Mac OS X instead of brew install node. See the nvm README for more details. Yeoman and Grunt installed: npm install -g yo grunt-cli
How I made this app
Grab my copy of generator-browserify (until this pull request is closed).
npm -g install ivanoats/generator-browserify
Generate the app skeleton
mkdir blog && cd blog yo browserify
Choose Grunt as the build system. Choose Foundation as the front-end framework. Yes, you'd like to include Modernizr to support your grand-dad on IE8. No, let's skip Jade templating for now. Choose Libsass as the sass compiler so that you don't need a Ruby dependency in your project
You'll see a lot of text scroll by, and on my system I saw the last lines like this:
[email protected] node_modules/grunt-sass ├── [email protected] └── [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected])
Your directory listing should look something like this:
total 80 drwxr-xr-x 13 ivan staff 442 Apr 17 12:40 . drwxr-xr-x 256 ivan staff 8704 Apr 17 12:36 .. -rw-r--r-- 1 ivan staff 42 Apr 16 15:14 .bowerrc -rw-r--r-- 1 ivan staff 214 Apr 16 15:14 .editorconfig -rw-r--r-- 1 ivan staff 11 Apr 16 15:14 .gitattributes -rw-r--r-- 1 ivan staff 65 Apr 16 15:14 .gitignore -rw-r--r-- 1 ivan staff 390 Apr 16 15:14 .jshintrc -rw-r--r-- 1 ivan staff 11094 Apr 17 12:40 Gruntfile.js drwxr-xr-x 7 ivan staff 238 Apr 17 12:40 app -rw-r--r-- 1 ivan staff 213 Apr 16 15:14 bower.json drwxr-xr-x 2 ivan staff 68 Apr 17 12:40 dist drwxr-xr-x 32 ivan staff 1088 Apr 17 12:40 node_modules -rw-r--r-- 1 ivan staff 1277 Apr 17 12:40 package.json Now type grunt serve to launch the app in a web browser. You should see something like this:
That's great but let's start with a simpler blog layout: Go to http://foundation.zurb.com/templates.html and download the blog layout HTML. Put that in the body tag of app/index.html in your project.
You can now start customizing your blog with the following files:
app/index.html app/scss/app.scss app/images
Here's what I did: Go to town! This generator also includes BackboneJS so you can even make your blog a single- page app. Roadmap for the future for this app
Add a simple MongoDB / Express app as the blog's REST API Build out the site with BackboneJS Add some CasperJS ZombieJS or SuperAgent tests. Contributing
Tested Pull-Requests welcome! I will list you as a contributor. Day Four
Agenda
Acceptance Testing with CasperJS Deploying to Heroku Sass, a CSS pre-processing language Acceptance Testing with CasperJS
Acceptance testing is also known as "Outside-in", or "black-box" testing. It tests a system just like a web browser does. Except, instead of a person clicking on a web browser, a "headless" browser operates in the command line, a bit more behind the scenes.
There are many options for acceptance testing, but we will be using one called CasperJS. Write our first acceptance test
Let's just test to see if the home page is loading o.k., and that the title tag and H1 tags are what we expect. Here's the code, it goes in test/acceptance/home_page_test.js:
BTW, if you want to make a new directory multiple levels deep, you can use: mkdir -p test/acceptance from your project's home directory.
'use strict'; /*global casper*/
casper.test.begin('home page', 3, function suite(test) {
casper.start('http://localhost:3000/', function() { test.assertHttpStatus(200); });
casper.then(function(){ test.assertTitle('Hello World Express', 'title is Hello World Express' });
casper.then(function() { test.assertSelectorHasText('h1','Hello World'); });
casper.run(function(){ test.done(); });
});
So, we have three assertions that we expect to be true. The status should be 200 OK, the title should be "Hello World Express", and the h1 should include the text "Hello World". Run our acceptance tests
To run our acceptance test we'll need to make sure to start the express server. We will use a grunt plugin to automate this.
You can do this on your personal portfolio site, or your hello world express code.
Hook up Grunt-Express-Server
From the command line: npm install grunt-express-server --save-dev
And in Gruntfile.js add: grunt.loadNpmTasks('grunt-express-server');
Install and Configure CasperJS and PhantomJS
Install Casper and PhantomJS globally, and Grunt integration locally
npm install -g phantomjs casperjs npm install grunt-casper --save-dev npm install grunt-express-server --save-dev
Edit your Gruntfile.js to include tasks like these below:
'use strict'; module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-express-server'); grunt.loadNpmTasks('grunt-casper');
grunt.initConfig({ express: { options: { // Override defaults here }, dev: { options: { script: 'server.js' } }, prod: { options: { script: 'server.js', node_env: 'production' } }, test: { options: { script: 'server.js' } } }, casper: { acceptance : { options : { test : true, }, files : { 'test/acceptance/casper-results.xml' : ['test/acceptance/*_test.js' } } } });
grunt.registerTask('server', [ 'jshint', 'express:dev' ]); grunt.registerTask('test',['express:dev','casper']); grunt.registerTask('default', ['jshint', 'test']);
};
I added a server task that runs the express server after JSHint passes. I added a test task that sets up the express server in dev mode, and then runs the casper tests. I set the default task to run JSHint and then the test task. Try it out
Now try grunt test from the command line and see what happens… Sass
Sass is CSS with Superpowers
Credit is due to Dale Sande for preparing this material.
Sass is an extension of CSS that adds power and elegance to the basic language. It allows you to use variables, nested rules, mixins, inline imports, and more, all with a fully CSS-compatible syntax. Sass helps keep large stylesheets well-organized, and get small stylesheets up and running quickly, particularly with the help of the Compass style library.
Is Sass somewhat of a mystery to you? How does it work? Why do some say that it is better then CSS?
Official documentation: http://sass-lang.com/documentation/file.SASS_REFERENCE.html More info: http://coderecipez.roughdraft.io Node Sass and Grunt
Sass was orignally a Ruby gem, but it is also available as an npm package now. You can npm install node-sass in your projects. Heroku
Let's get our site LIVE ON THE WEB!! This process is called deployment. Slides
Slides from class introducing Heroku. Installation
Make sure you have the Heroku Toolbelt installed.
You can usually brew install heroku-toolbelt or sudo apt-get install heroku-toolbelt. If those don't work you may need to donwload it.
Also, if you haven't already, sign up for an account on Heroku.com. Login
Use heroku login to log in to heroku from the command line.
If you're already logged in, you can use heroku auth:whoami to see who you are logged in as. Create a heroku app
You'll want a nice name for your app instead of the random ones Heroku gives you.
E.g. heroku create ivan-hello-world-express Create the Procfile
You need a file to tell heroku how to launch your app.
Edit Procfile which should be in the root directory of your project. No file extension on this file, and it needs to start with a Capital letter. The procfile is simply:
web: node server.js
This tells heroku that to start your web server, it needs to run the command node server.js Test it out locally with node-foreman
You can use a npm package called foreman to test that your Procfile works as expected. Install this globally. npm install -g foreman
This will give you the nf command. Try it out. nf --help
And, now, try starting your server via foreman. nf start
It should start up your server on port 5000 as a default.
This means that your server should not have any port 'hard-coded' as a default (like 3000). Make sure your server code looks something like this:
var server = http.createServer(app); app.set('port', process.env.PORT || 3000);
server.listen(app.get('port'), function() { console.log('the server is NOW running on port', app.get('port')); }); Commit any changes and push to Heroku
Make sure to commit any changes you made to your app, like adding the Procfile, etc. git add . git commit -m 'preparing for heroku'
Make sure you're on the master branch or that you merge you changes back to master.
And now, to deploy your app to the web on Heroku: git push heroku master
You'll see a bunch of info scroll by from Heroku, but it should look something like this:
$ git push heroku master Fetching repository, done. Counting objects: 7, done. Delta compression using up to 8 threads. Compressing objects: 100% (3/3), done. Writing objects: 100% (4/4), 343 bytes | 0 bytes/s, done. Total 4 (delta 2), reused 0 (delta 0)
-----> Node.js app detected
PRO TIP: Specify a node version in package.json See https://devcenter.heroku.com/articles/nodejs-support
-----> Defaulting to latest stable node: 0.10.28 -----> Downloading and installing node -----> Restoring node_modules directory from cache -----> Pruning cached dependencies not specified in package.json npm WARN package.json hello-express@ No repository field. -----> Writing a custom .npmrc to circumvent npm bugs -----> Exporting config vars to environment -----> Installing dependencies npm WARN package.json hello-express@ No repository field. -----> Caching node_modules directory for future builds -----> Cleaning up node-gyp and npm artifacts -----> Building runtime environment -----> Discovering process types Procfile declares types -> web
-----> Compressing... done, 5.3MB -----> Launching... done, v4 http://ivan-hello-world-express.herokuapp.com/ deployed to Heroku
To [email protected]:ivan-hello-world-express.git 3d47745..3f34feb master -> master
And you can open your browser, and visit your app on the web! Day Five
Fridays are guest speaker days. Each guest speaker varies by availability. Day Six
Monday, welcome back! How were the weekend readings? Agenda
Discuss readings on Modular JavaScript, CommonJS, Code Complexity and Clean Code Browserify Browserify Lab RequireJS Stretch goals: ECMAScript6/Harmony modules Day Six Readings
We are loading you up on best practices readings for the weekend. We will practice using these strategies for the rest of the development accelerator. Rationale
Read Preface and Chapters 1-2 of Testable JavaScript Read Chapter 1 of Clean Code Implementation
Modular JavaScript and CommonJS
Read about the basics of Node’s Require and Exports: http://openmymind.net/2012/2/3/Node-Require-and-Exports/ Dive deeper into exports: http://bites.goodeggs.com/posts/export-this/ Read about CommonJS: http://dailyjs.com/2010/10/18/modules/ Read about modular Javascript, especially the section on CommonJS: http://addyosmani.com/writing-modular-js/ Read NodeJS Require best practices: http://www.mircozeiss.com/node-js-require-s-best- practices/
Now, you're ready to go on to Browserify. Browserify
Use your modules, plus already existing node core modules, in the browser
includes assert, path, url, crypto, domain, events, querystring, util, buffer, etc… bundles up modules into one file, increasing performance What Code is a Good Candidate for Browserify?
Anything you want to use on the server and in the browser.
Validation - ensuring data from the user is in an acceptable format. For example, an email must have an @ sign and a "." Alternatives to Browserify
RequireJS ECMAScript 6 built in modules
Others Automation and Distribution
grunt-contrib-concat For JS can be replaced by Browserify grunt-contrib-copy For HTML, Images, plain CSS grunt-contrib-connect grunt-contrib-watch But wait, what about Bower?
bower install does not modify package.json You could still use
Hello World!