SlideShare a Scribd company logo
Practical JavaScript Programming
Session 8
Wilson Su
2
https://www.slideshare.net/sweekson/
3
Wilson Su
Front-end Developer, HIE
● 6 years in web design
● Specialize in JavaScript /
CSS / HTML / OOP / Git
● Familiar with PHP / Design
Pattern
● Interested in UI & Ix Design
wilson_su@trend.com.tw
Outline
4
Practical JavaScript Programming
Chapter 17.
● Node.js
● TypeScript
● Babel
● Linter
Development Tools
● Task Runner
● Module Bundler
● Chrome DevTools
● Testing Tools
Chapter 17.
Development Tools
5
Node.js
6
7
Node.js
https://nodejs.org/
8
npm
https://www.npmjs.com/
9
Creating a Project and Installing Dependencies
1. $ mkdir webapp
2. $ cd webapp
3. $ npm init
4. $ npm install express --save
Sample package.json
10
1. {
2. "name": "webapp",
3. "version": "0.1.0",
4. "description": "A simple web app with Express.",
5. "author": "Rick <rick@mail.fed.com>",
6. "dependencies": {
7. "express": "^4.15.3"
8. }
9. }
Project Structure
11
Node.js
webapp
public
index.html
create.html
package.json
server.js
The project metadata for npm
app.js
create.html
node_modules Dependencies are downloaded into this folder
https://github.com/sweekson/tm-etp-webapp
./server.js
12
1. var express = require('express');
2. var app = express();
3. var port = process.env.PORT;
4. app.use(express.static('public'));
5. app.listen(port, function (err) {
6. if (err) { throw err; }
7. console.log('Listening on port ' + port);
8. });
13
A Simple Web App
https://webapp-wilson-su.c9users.io/
14
Yarn
https://yarnpkg.com/en/
Yarn Installation and Usage
15
1. $ curl -sS "https://dl.yarnpkg.com/debian/pubkey.gpg" | sudo
apt-key add -
2. $ echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo
tee /etc/apt/sources.list.d/yarn.list
3. $ sudo apt-get update
4. $ sudo apt-get install yarn
5. $ mkdir webapp
6. $ cd webapp
7. $ yarn init
8. $ yarn add express
TypeScript
16
17
TypeScript
https://www.typescriptlang.org/
TypeScript Installation and Usage
18
1. $ npm install typescript --save-dev
2. $ sudo npm install typescript --global
3. $ tsc --init
Sample tsconfig.json
19
1. {
2. "compilerOptions": {
3. "target": "es5",
4. "module": "commonjs",
5. "outDir": "./dist",
6. "moduleResolution": "node"
7. },
8. "include": [
9. "src/**/*"
10. ]
11. }
20
Adds Types to Function
1. function greet (name: string): string {
2. return `Hello, ${name}.`;
3. }
4.
5. greet('TypeScript'); // 'Hello, TypeScript.'
6. greet([1, 2, 3]); // Error
Use an Interface
21
1. interface User {
2. id: number | string,
3. name: string,
4. age?: number
5. }
6. function echo(user: User): string {
7. return `#${user.id} ${user.name} (${user.age || '?'})`;
8. }
9.
10. echo({ id: 15, name: 'Tina' }); // '#15 Tina (?)'
11. echo({ id: '36', name: 'Eric', age: 20 }); // '#36 Eric (20)'
12. echo({}); // Error
Use Generics
22
1. function echo<T> (list: T[]): T[] {
2. return list;
3. }
4. echo<string>(['x', 'y', 'z']); // (3) ['x', 'y', 'z']
5. echo<number>([1, 2, 3]); // (3) [1, 2, 3]
Babel
23
24
Babel
https://babeljs.io/
Sample .babelrc
25
1. {
2. "presets": ["es2015"],
3. "plugins": ["transform-exponentiation-operator"],
4. "comments": false
5. }
Writing Next Generation JavaScript - Example 1
26
1. /* Next-gen JavaScript */
2. var skill = 'JavaScript';
3. console.log(`Hellom, ${skill}.`);
4.
5. /* Browser-compatible JavaScript */
6. var skill = 'JavaScript';
7. console.log('Hello, ' + skill + '.');
Writing Next Generation JavaScript - Example 2
27
1. /* Next-gen JavaScript */
2. function add (a = 0, b = 0) {
3. return a + b;
4. }
5.
6. /* Browser-compatible JavaScript */
7. function add () {
8. var a = arguments.length > 0 && arguments[0] !== undefined ?
arguments[0] : 0;
9. var b = arguments.length > 1 && arguments[1] !== undefined ?
arguments[1] : 0;
10. return a + b;
11. }
28
Writing Next Generation JavaScript - Example 3
1. /* Next-gen JavaScript */
2. [1, 2, 3].map(n => n ** 2);
3.
4. /* Browser-compatible JavaScript */
5. [1, 2, 3].map(function (n) {
6. return Math.pow(n, 2);
7. });
Linter
29
30
What Is Lint?
In computer programming, lint is a Unix utility that flags some suspicious
and non-portable constructs in C language source code. Lint as a term can
also refer more broadly to syntactic discrepancies in general, especially in
interpreted languages like JavaScript. For example, modern lint checkers
are often used to find code that doesn't correspond to certain style
guidelines. – Wiki
Linter
31
ESLint
http://eslint.org/
ESLint Installation and Usage
32
1. $ npm install eslint --save-dev
2. $ sudo npm install eslint --global
3. $ npm install eslint-config-airbnb --save-dev
4. $ eslint --init
33
Sample .eslintrc.js
1. module.exports = {
2. extends: 'airbnb-base',
3. rules: {
4. strict: 'error',
5. semi: ['error', 'always'],
6. indent: ['error', 2],
7. eqeqeq: ['error', 'always'],
8. 'no-var': 'error'
9. }
10. };
34
TSLint
https://palantir.github.io/tslint/
Sample tslint.json
35
1. {
2. "defaultSeverity": "error",
3. "extends": "tslint:recommended",
4. "rules": {
5. "semicolon": [true, "always"],
6. "indent": [true, "spaces", 2],
7. "triple-equals": [true, "allow-null-check"],
8. "no-var-keyword": true
9. }
10. }
Task Runner
36
What Is Task Runner?
37
Task Runner
A task runner is a tool used to automatically perform repetitive tasks.
Common tasks in web development including:
Linting ConcatenationCompilation
Minification
Watching File
Changes
Unit Testing …
38
Grunt
https://gruntjs.com/
Sample Gruntfile.js
39
1. module.exports = function (grunt) {
2. grunt.initConfig({
3. less: {
4. files: [{ src: 'src/less/*.less', dest: 'build/css' }]
5. },
6. copy: {
7. files: [{ src: 'src/tmpl/*.html', dest: 'build/views' }]
8. }
9. });
10. grunt.loadNpmTasks('grunt-contrib-less');
11. grunt.loadNpmTasks('grunt-contrib-copy');
12. grunt.registerTask('default', ['less', 'copy']);
13. };
40
Gulp
https://gulpjs.com/
41
Sample gulpfile.js
1. var gulp = require('gulp');
2. var less = require('gulp-less');
3. gulp.task('html', function () {
4. return gulp.src('src/tmpl/*.html')
5. .pipe(gulp.dest('build/views'));
6. });
7. gulp.task('css', function () {
8. return gulp.src('src/less/*.less')
9. .pipe(less()).pipe(gulp.dest('build/css'));
10. });
11. gulp.task('default', ['html', 'css']);
Module Bundler
42
43
Webpack
https://webpack.js.org/
44
Sample Webpack Config
1. var path = require('path');
2. module.exports = {
3. entry: './src/app.js',
4. output: {
5. path: path.join(__dirname, 'build'), filename: 'bundle.js'
6. },
7. module: {
8. loaders: [{ test: /.less$/, loader: 'style!css!less' }]
9. }
10. };
Chrome DevTools
45
Chrome DevTools
46
The DevTools Window
Elements Network Sources
Console Application Performance
Memory Audits Security
47
Elements Panel
48
Node Tree CSS Styles
49
Interact With a DOM Node
50
Computed Styles
51
Event Listeners
52
Properties
53
Network Panel
54
Network Throttling
55
Filters
56
Request and Response Headers
57
Response Preview
58
Cookies
59
Sources Panel
60
DebuggerNavigator Source Content
61
Formatted Source Content
62
Inspect and Debug
63
64
Conditional Breakpoints
65
Breakpoints
66
Console Panel
67
Console Settings
1. console.debug(object[, object, …]);
2. console.info(object[, object, …]);
3. console.log(object[, object, …]);
4. console.warn(object[, object, …]);
5. console.error(object[, object, …]);
6. console.dir(object);
7. console.table(array);
8. console.count([label]);
9. console.trace(object[, object, …]);
10. console.time([label]);
11. console.timeEnd([label]);
68
Working With the Console
69
Printing Messages
70
Filtering the Console Output
71
Printing HTML Element With console.log()
72
Printing HTML Element With console.dir()
73
Printing an Array
74
Writes the Number of Times That count() Has Been Invoked
75
Prints a Stack Trace
76
Starts and Stops a Timer
77
Application Panel
78
79
Performance Panel
80
81
Memory Panel
82
83
Audits Panel
84
85
Security Panel
86
Testing Tools
87
88
Unit Tests VS. E2E Tests
Testing
Unit Tests E2E Tests
White-box Black-box
APIs UIs
JavaScript JavaScript / HTML
Console Browsers
89
Jasmine
https://jasmine.github.io/
90
Sample Test Code
1. function multiply (a, b) {
2. return a * b;
3. }
4. describe('Calculator', function () {
5. it('multiply method should be implemented', function () {
6. expect(multiply).toBeDefined();
7. });
8. it('multiply method should multiply values', function () {
9. expect(multiply(6, 4)).toBe(24);
10. });
11. });
91
Mocha
https://mochajs.org/
Sample Test Code
92
1. var assert = require('assert');
2. describe('Math#max()', function () {
3. it('should return the largest number', function () {
4. assert.equal(5, Math.max(3, 5, 1));
5. });
6. });
93
Chai
http://chaijs.com/
Sample Assertions
94
1. var assert = chai.assert;
2. var expect = chai.expect;
3. var lib = 'chai';
4. assert.typeOf(lib, 'string');
5. assert.equal(lib, 'chai');
6. assert.lengthOf(lib, 4);
7. expect(lib).to.be.a('string');
8. expect(lib).to.equal('chai');
9. expect(lib).to.have.lengthOf(4);
95
Karma
https://karma-runner.github.io/
96
Selenium
http://www.seleniumhq.org/
97
Protractor
http://www.protractortest.org/
98
Sample Test Code
1. describe('Todo list', function () {
2. it('should add a todo task', function () {
3. browser.get('https://app.todos.net');
4. element(by.css('#task')).sendKeys('Water');
5. element(by.css('[value="add"]')).click();
6. var todos = element.all(by.css('.todo'));
7. expect(todos.count()).toEqual(3);
8. expect(todos.get(2).getText()).toEqual('Water');
9. });
10. });
99
Phantom
http://phantomjs.org/
100
CasperJS
http://casperjs.org/
Sample Test Code
101
1. var casper = require('casper').create();
2. casper.start('https://reports.car.com');
3. casper.thenClick('#btn-month');
4. casper.then(function () {
5. phantomcss.screenshot('#dashboard', 'dashboard');
6. });
7. casper.then(function () {
8. phantomcss.compareAll();
9. });
10. casper.run();
102
Visual Regression Testing
Testing
But wait! There’s still much
more you need to learn …
103
104
JS
HTML
CSS
UI
Testing
Backbone
Veu.js
JSON
jQuery
DOM
React
BOM
Angular
TypeScript
AJAX
Usability
RegExp
WebSocket
Less
SCSS
CSS Module
Sass
DevTools
CasperJS
Jasmine
Karma
Mocha
WebDriver
Protractor
Lint
Accessibility
UI Design
RWDCanvasSVG
D3
WebGL
SQL
MySQLPHPMongoDB
Express
SEO
Babel
Performance
REST
Security
Grunt
Gulp
Webpack
Animation
Stylus
Bootstrap
What You Need to Be a Front-end Developer
Reference
105
● Lint (software) - Wikipedia
● eslint-config-airbnb at master ‧ airbnb/javascript
● Chrome DevTools | Web | Google Developers
● Visual Regression Testing with PhantomCSS | CSS-Tricks
● JavaScript Testing Framework Comparison: Jasmine vs Mocha |
Codementor
Practical JavaScript Programming
Questions?
106
THANKS

More Related Content

PDF
Practical JavaScript Programming - Session 5/8
PDF
Practical JavaScript Programming - Session 7/8
PDF
Mirage For Beginners
PDF
Practical JavaScript Programming - Session 4/8
PDF
Practical JavaScript Programming - Session 6/8
PDF
Practical JavaScript Programming - Session 1/8
PDF
Workshop 5: JavaScript testing
PPTX
Workshop 1: Good practices in JavaScript
Practical JavaScript Programming - Session 5/8
Practical JavaScript Programming - Session 7/8
Mirage For Beginners
Practical JavaScript Programming - Session 4/8
Practical JavaScript Programming - Session 6/8
Practical JavaScript Programming - Session 1/8
Workshop 5: JavaScript testing
Workshop 1: Good practices in JavaScript

What's hot (20)

PDF
Workshop 10: ECMAScript 6
PPTX
JavaScript Proven Practises
PDF
Owasp orlando, april 13, 2016
PDF
Practical Google App Engine Applications In Py
PDF
Inversion Of Control
ODP
Introduccion a Jasmin
PDF
05 JavaScript #burningkeyboards
PDF
Formacion en movilidad: Conceptos de desarrollo en iOS (IV)
PDF
Impact of the New ORM on Your Modules
PPTX
Java Bytecode: Passing Parameters
PPTX
Angular 2 Architecture
PPTX
Component lifecycle hooks in Angular 2.0
PPTX
Avoiding callback hell in Node js using promises
PDF
Testing your javascript code with jasmine
PDF
Asynchronous JS in Odoo
PDF
06 jQuery #burningkeyboards
PPTX
Metaprogramming in ES6
PPTX
Angular 2.0 Views
PDF
JavaScript Unit Testing with Jasmine
PPTX
Unit testing CourseSites Apache Filter
Workshop 10: ECMAScript 6
JavaScript Proven Practises
Owasp orlando, april 13, 2016
Practical Google App Engine Applications In Py
Inversion Of Control
Introduccion a Jasmin
05 JavaScript #burningkeyboards
Formacion en movilidad: Conceptos de desarrollo en iOS (IV)
Impact of the New ORM on Your Modules
Java Bytecode: Passing Parameters
Angular 2 Architecture
Component lifecycle hooks in Angular 2.0
Avoiding callback hell in Node js using promises
Testing your javascript code with jasmine
Asynchronous JS in Odoo
06 jQuery #burningkeyboards
Metaprogramming in ES6
Angular 2.0 Views
JavaScript Unit Testing with Jasmine
Unit testing CourseSites Apache Filter
Ad

Similar to Practical JavaScript Programming - Session 8/8 (20)

PDF
Learning Nodejs For Net Developers Harry Cummings
PDF
JavaScript in 2015
PDF
JavaScript for impatient programmers.pdf
PDF
Modern front-end Workflow
PDF
JavaScript Good Practices
PDF
React Native One Day
PDF
Node.js - async for the rest of us.
PDF
You Don t Know JS ES6 Beyond Kyle Simpson
PDF
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
PDF
Node Boot Camp
PDF
Full Stack Developer Course | Infinite Graphix Technologies
PPTX
Intro To Node.js
PPTX
TDD and the Legacy Code Black Hole
PPTX
JS & NodeJS - An Introduction
PDF
DownTheRabbitHole.js – How to Stay Sane in an Insane Ecosystem
PDF
Node.JS briefly introduced
PDF
Angular Weekend
PPTX
Overview of Node JS
PPTX
Introducing Node.js in an Oracle technology environment (including hands-on)
PDF
How to-node-core
Learning Nodejs For Net Developers Harry Cummings
JavaScript in 2015
JavaScript for impatient programmers.pdf
Modern front-end Workflow
JavaScript Good Practices
React Native One Day
Node.js - async for the rest of us.
You Don t Know JS ES6 Beyond Kyle Simpson
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Node Boot Camp
Full Stack Developer Course | Infinite Graphix Technologies
Intro To Node.js
TDD and the Legacy Code Black Hole
JS & NodeJS - An Introduction
DownTheRabbitHole.js – How to Stay Sane in an Insane Ecosystem
Node.JS briefly introduced
Angular Weekend
Overview of Node JS
Introducing Node.js in an Oracle technology environment (including hands-on)
How to-node-core
Ad

More from Wilson Su (7)

PDF
NestJS
PDF
The Jira How-To Guide
PDF
The Future of Web Development
PDF
Web Usability
PDF
Puppeteer - Headless Chrome Node API
PDF
Practical JavaScript Programming - Session 3/8
PDF
Practical JavaScript Programming - Session 2/8
NestJS
The Jira How-To Guide
The Future of Web Development
Web Usability
Puppeteer - Headless Chrome Node API
Practical JavaScript Programming - Session 3/8
Practical JavaScript Programming - Session 2/8

Recently uploaded (20)

PPTX
OOP with Java - Java Introduction (Basics)
PDF
PPT on Performance Review to get promotions
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPT
Mechanical Engineering MATERIALS Selection
PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PPT
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPTX
Sustainable Sites - Green Building Construction
PDF
R24 SURVEYING LAB MANUAL for civil enggi
DOCX
573137875-Attendance-Management-System-original
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PPTX
Geodesy 1.pptx...............................................
PPT
Project quality management in manufacturing
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
OOP with Java - Java Introduction (Basics)
PPT on Performance Review to get promotions
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
Mechanical Engineering MATERIALS Selection
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
Sustainable Sites - Green Building Construction
R24 SURVEYING LAB MANUAL for civil enggi
573137875-Attendance-Management-System-original
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
Geodesy 1.pptx...............................................
Project quality management in manufacturing
Mitigating Risks through Effective Management for Enhancing Organizational Pe...

Practical JavaScript Programming - Session 8/8