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

Practical JavaScript Programming - Session 8/8