Contenu connexe Similaire à Practical JavaScript Programming - Session 8/8 (20) Practical JavaScript Programming - Session 8/83. 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
9. 9
Creating a Project and Installing Dependencies
1. $ mkdir webapp
2. $ cd webapp
3. $ npm init
4. $ npm install express --save
10. 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. }
12. ./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. });
15. 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
18. TypeScript Installation and Usage
18
1. $ npm install typescript --save-dev
2. $ sudo npm install typescript --global
3. $ tsc --init
19. 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. 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
21. 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
22. 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]
25. Sample .babelrc
25
1. {
2. "presets": ["es2015"],
3. "plugins": ["transform-exponentiation-operator"],
4. "comments": false
5. }
26. 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 + '.');
27. 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. 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. });
30. 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
32. 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. 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. };
35. 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. }
37. 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 …
39. 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. };
41. 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']);
44. 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. };
68. 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
88. 88
Unit Tests VS. E2E Tests
Testing
Unit Tests E2E Tests
White-box Black-box
APIs UIs
JavaScript JavaScript / HTML
Console Browsers
90. 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. });
92. 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. });
94. 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);
98. 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. });
101. 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();
105. 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