Slide 1

Slide 1 text

What's happening in frontend now? YAPC::Asia 2015 (8/21) @koba04

Slide 2

Slide 2 text

koba04 • Toru Kobayashi • Web application engineer • ≠ Frontend engineer • Single Page Application • Backbone -> Angular -> React

Slide 3

Slide 3 text

Agenda • Ajax ʙ • Language • Web Application • Tools • Environment

Slide 4

Slide 4 text

2005 2015 Ajax ECMAScript 5 ECMAScript 2015

Slide 5

Slide 5 text

Once upon a time…

Slide 6

Slide 6 text

Good old web • Client requests HTML. • Server responses HTML. • Very simple • JavaScript doesn’t have to use. browser server GET /index.html index.html GET /about.html about.html

Slide 7

Slide 7 text

Ajax! • Google Map • Asynchronous updates • We need JavaScript! • From Page to Application

Slide 8

Slide 8 text

We need to write JavaScript…

Slide 9

Slide 9 text

Language

Slide 10

Slide 10 text

ECMAScript 5

Slide 11

Slide 11 text

ECMAScript 5 (5.1) • “use strict”; • Object.create, Object.defineProperty • Array.prototype.(forEach, map, filter, reduce…) • JSON.parse, JSON.stringify • IE9ʙ 2009 2011(5.1)

Slide 12

Slide 12 text

CoffeeScript

Slide 13

Slide 13 text

CoffeeScript • Jeremy Ashkenas • CoffeeScript is a little language that compiles into JavaScript • Brevity and readability. • Rails 3.1 CoffeeScript • Some features are in ECMAScript 2015 2010(1.0)

Slide 14

Slide 14 text

class Parent class Hello extends Parent constructor: (@name) -> super() method: -> console.log @name hello = new Hello 'coffee' setTimeout( () => hello.method(), 1000 )

Slide 15

Slide 15 text

Web Application

Slide 16

Slide 16 text

jQuery

Slide 17

Slide 17 text

jQuery • John Resig • DOM API is too low level • Browsers compatibility • jQuery Plugin • document.querySelector, Deferred(Promise)… 2006

Slide 18

Slide 18 text

$button.on(‘click’, function() { $.ajax( method: ‘GET’, url: ‘/api/item_list’ ) .done(function(items) { $ul = $(‘
    ’); $.each(items, function(index, value) { $ul.append($(‘
  • ’ + value + ‘
  • ’)); }); $(‘.items’).append($ul); }); }); });

    Slide 19

    Slide 19 text

    No content

    Slide 20

    Slide 20 text

    Backbone.js

    Slide 21

    Slide 21 text

    Backbone.js • Jeremy Ashkenas • JavaScript MVC framework • Observer pattern • Depend on jQuery & underscore.js 2010

    Slide 22

    Slide 22 text

    Backbone.Collection Backbone.View Backbone.Model Backbone.Model Backbone.Router Backbone.Event Backbone.History

    Slide 23

    Slide 23 text

    var View = Backbone.View.extend({ events: { 'change .text': 'change' }, initialize: function() { this.listenTo(this.model, 'change', this.render); }, change: function() { this.model.set('text', this.$el.find('.text').val()); }, render: function() { this.$el.html( '
    ' + this.model.get('text') + ‘
    ' ); return this; } }); $('#app').append( new View({ model: new Backbone.Model({text: ‘initial'}) }).render().$el );

    Slide 24

    Slide 24 text

    Tools

    Slide 25

    Slide 25 text

    Node.js

    Slide 26

    Slide 26 text

    Node.js • Node.js is a platform built on V8 • npm (173,476 packages) • server & cli • Event loop is that it runs under a single thread • Stream 2009

    Slide 27

    Slide 27 text

    var http = require('http'); var fs = require('fs'); http.createServer(function(req, res) { fs.readFile('test.png', function(err, data) { if (err) return console.log(err); res.writeHead(200, {'Content-Type': 'image/png'}); res.end(data); }); }).listen(3000); // ↓ http.createServer(function(req, res) { fs.createReadStream('test.png').pipe(res); }).listen(3001); Stream!

    Slide 28

    Slide 28 text

    Grunt

    Slide 29

    Slide 29 text

    Grunt.js • The JavaScript Task Runner • Not a build tool • Configurable • Yeomanɺassemble • Last release is 2014 May… • npm scripts 2012

    Slide 30

    Slide 30 text

    CoffeeScript Port JavaScript watch JavaScript Running Webserver Minified JavaScript Output files Src files compile uglify exec

    Slide 31

    Slide 31 text

    module.exports = (grunt) -> watch: coffee: files: ["coffee/**/*.coffee"] tasks: ["js"] coffee: files: "static/js/app.js": [ "coffee/app.coffee" "coffee/model/*.coffee" "coffee/collection/*.coffee" "coffee/view/*.coffee" ] concat: dev: src: [ "bower_components/jquery/jquery.js" "bower_components/underscore/underscore.js" "bower_components/backbone/backbone.js" "static/js/app.js" ] dest: “static/js/all.js"

    Slide 32

    Slide 32 text

    Environment

    Slide 33

    Slide 33 text

    Chrome

    Slide 34

    Slide 34 text

    Chrome • Fast! Fast! Fast! • Webkit (version 28ʙ Blink) • Google V8 JavaScript Engine • JavaScriptCore(Safari), Chakra(IE), SpiderMonkey(Firefox) • Just in Time (JIT) 2008

    Slide 35

    Slide 35 text

    Single Page Application

    Slide 36

    Slide 36 text

    Language

    Slide 37

    Slide 37 text

    TypeScript

    Slide 38

    Slide 38 text

    TypeScript • Microsoft • Typed superset of JavaScript • Class, Interface, Generics, Modules… • IDE Support • DefinitelyTyped 2012

    Slide 39

    Slide 39 text

    class Greeter { greeting: string; constructor(message: string) { this.greeting = message; } greet(): string { return "Hello, " + this.greeting; } } var greeter = new Greeter("world");

    Slide 40

    Slide 40 text

    AST

    Slide 41

    Slide 41 text

    AST • Abstract Syntax Tree • SpiderMonkey Parser API • https://developer.mozilla.org/en-US/docs/ Mozilla/Projects/SpiderMonkey/Parser_API • Esprima, Espree, Acorn, Babylon • ESTree, ShiftAST

    Slide 42

    Slide 42 text

    var answer = hoge * 7; VariableDeclarator Identifier answer Identifier hoge BinaryExpression * Literal 7

    Slide 43

    Slide 43 text

    { "type": "Program", "body": [ { "type": "VariableDeclaration", "declarations": [ { "type": "VariableDeclarator", "id": { "type": "Identifier", "name": "answer" }, "init": { "type": "BinaryExpression", "operator": "*", "left": { "type": "Identifier", "name": "hoge" }, "right": { "type": "Literal", "value": 7, "raw": "7" } } } ], "kind": "var" } ] } var answer = hoge * 7; Parse by Esprima http://esprima.org/demo/parse.html

    Slide 44

    Slide 44 text

    Your JavaScript Espree Acorn … AST Transpile Lint Analyze

    Slide 45

    Slide 45 text

    Libraries using AST • Linter - ESLint • Analyzer - istanbul, plato • Test - power-assert • Transpiler - browserify, babel

    Slide 46

    Slide 46 text

    Web Application

    Slide 47

    Slide 47 text

    https://blog.twitter.com/2012/improving-performance-on-twittercom

    Slide 48

    Slide 48 text

    Problems of SPA • SEO • Performance(initial load) • Maintenance browser server HTML JavaScript JSON Data

    Slide 49

    Slide 49 text

    Isomorphic (Universal JavaScript)

    Slide 50

    Slide 50 text

    Isomorphic • Share the code between client and server • → For maintenance • Initial render executes on the server • → For SEO and Performance • Frameworks have different approaches • Meteor, Rendr…

    Slide 51

    Slide 51 text

    browser server HTML included contents GET app.js GET / Node.js You can see the contents! Start to run your JavaScript on the browser GET /other/page Route on the browser

    Slide 52

    Slide 52 text

    The requirements of SPA • Binding JSON data to DOM • Routing by the browser History API • Browser side template engine • Data management • Memory management

    Slide 53

    Slide 53 text

    Angular.js

    Slide 54

    Slide 54 text

    Angular.js • Google • HTML enhanced for web apps. • 2way Data binding • Full stack (ng-http, ng-router…) • Very simple? (initially) • Angular 2 is completely different. release:2009 1.0: 2012

    Slide 55

    Slide 55 text

    Slide 56

    Slide 56 text

    Tools

    Slide 57

    Slide 57 text

    SPA is… • Many assets files • JavaScript, CSS, template… • Hard to manage concatenating with Grunt • Increase a build time…

    Slide 58

    Slide 58 text

    gulp

    Slide 59

    Slide 59 text

    gulp • Stream base build system • Simple tasks pipe as stream • Programmable not configurable • Simple API • task, run, watch, src, dest 2014

    Slide 60

    Slide 60 text

    CoffeeScript Stream pipe Src files Stream pipe gulp.src coffee Stream pipe Stream pipe gulp.dest Files dest files

    Slide 61

    Slide 61 text

    var gulp = require('gulp'); var concat = require(‘gulp-concat'); var coffee = require('gulp-coffee'); var uglify = require('gulp-uglify'); var coffeeFiles = './src/**/*.coffee'; gulp.task('compile', function(){ gulp.src(coffeeFiles) ����.pipe(coffee()) .pipe(concat(‘app.js’)) .pipe(uglify()) .pipe(gulp.dest(‘dist’)); }); gulp.task(‘watch’, function() { gulp.watch(coffeeFiles, ['compile']); });

    Slide 62

    Slide 62 text

    browserify

    Slide 63

    Slide 63 text

    browserify • substack • Browserify lets you require('modules') in the browser by bundling up all of your dependencies. • No more concatenating which is depending on the order • It makes possible to share code between the browser and server. 2013

    Slide 64

    Slide 64 text

    require(‘./foo’); require(‘./bar’); bundle.js app.js require(‘events’); require(‘react’); … … bar.js foo.js events react

    Slide 65

    Slide 65 text

    StatelessɾComposableɾ Stream

    Slide 66

    Slide 66 text

    Language

    Slide 67

    Slide 67 text

    ECMAScript 2015

    Slide 68

    Slide 68 text

    ECMAScript 2015 • ECMAScript 6 • JavaScript is more powerful. • Class, Modules, Arrow Function, Promise… • Destructuring assignment — • Browsers haven’t supported all features yet. 2015 June

    Slide 69

    Slide 69 text

    http://kangax.github.io/compat-table/es6/

    Slide 70

    Slide 70 text

    class Person { method(val=“default”) { console.log(val); } method2(...array) { return new Promise((resolve, reject) => { setTimeout(() => { resolve(array.map(val => val * 2)); }, 1000); }); } } const person = new Person(); person.method2(1, 2, 3).then(array => console.log(array)); // [2, 4, 6] const user = {name: ‘Jim’, age: 20}; const {name, age} = user;

    Slide 71

    Slide 71 text

    Babel

    Slide 72

    Slide 72 text

    Babel • Sebastian McKenzie • JavaScript transpiler • Use next generation JavaScript, today. • We can use ECMAScript 2015 now! • Stage option (default is stage2) ʙ 5.x 2014

    Slide 73

    Slide 73 text

    TC39 • Technical Committee 39 • proposals into 4 stages • Stage 0 - Strawman • Stage 1 - Proposal • Stage 2 - Draft • Stage 3 - Candidate • Stage 4 - Finished

    Slide 74

    Slide 74 text

    https://github.com/tc39/ecma262

    Slide 75

    Slide 75 text

    Environment

    Slide 76

    Slide 76 text

    Service Workers

    Slide 77

    Slide 77 text

    Service Workers • JavaScript is more powerful. • Run independently of web pages. • Intercept Request • Offline / Cache • Background Sync • Push Notification • HTTPS Only

    Slide 78

    Slide 78 text

    // index.js if ('serviceWorker' in navigator) { navigator.serviceWorker.register('sw.js').then( sw => console.log('success'), err => console.log('error', err) ); } // sw.js self.addEventListener('install', sw => console.log('oninstall')); self.addEventListener('fetch', ev => { if (ev.request.url.indexOf('test') !== -1) { ev.respondWith(new Response('Hello Service Worker')); } });

    Slide 79

    Slide 79 text

    No content

    Slide 80

    Slide 80 text

    Extensible Web

    Slide 81

    Slide 81 text

    Extensible Web • The Extensible Web Manifesto • https://extensiblewebmanifesto.org/ • New low-level capabilities • Virtuous cycle • Prioritize efforts • Web Components ➜ Polymer

    Slide 82

    Slide 82 text

    Web Application

    Slide 83

    Slide 83 text

    React.js

    Slide 84

    Slide 84 text

    React.js • Facebook • Stateless Component • Mutability ➜ Complexity • Declarative programming • VIRTUAL DOM • Isomorphic! 2014

    Slide 85

    Slide 85 text

    ᶃ USJHHFS BOFWFOU ᶄFWFOU ᶅVQEBUFBTUBUF ᶆQBTTFTBTUBUFBTQSPQT ᶇVQEBUF%0. CZQSPQT Stateful Stateless

    Slide 86

    Slide 86 text

    class App extends React.Component { constructor(...args) { super(args); this.state = {count: 0}; } onClick() { this.setState({count: this.state.count + 1}); } render() { const {count} = this.state; return (

    {count}

    click
    ); } } React.render(, document.getElementById(‘app’));

    Slide 87

    Slide 87 text

    Flux

    Slide 88

    Slide 88 text

    Flux • Facebook • An application Architecture for Building User Interfaces • Unidirectional data flow

    Slide 89

    Slide 89 text

    Function Reactive Programming

    Slide 90

    Slide 90 text

    Functional Reactive Programming • Asynchronous data streams • A stream is a sequence of ongoing events ordered in time. • Mouse event, touch event, fetch response… • Observer and observable • Rx.js, Bacon.js, ECMAScript Observable(stage1)

    Slide 91

    Slide 91 text

    const $ = document.querySelector.bind(document); const plus = Rx.Observable.fromEvent($('#plus'), 'click'); const minus = Rx.Observable.fromEvent($('#minus'), 'click'); plus .map(1) .merge(minus.map(-1)) .scan((acc, value) => acc + value) .subscribe(value => sum.textContent = value) ;

    Slide 92

    Slide 92 text

    click plus click minus click minus click plus click plus plus.map(1) minus.map(-1) scan((acc, value) => acc + value) -1 1 -1 1 1 1 0 -1 0 1

    Slide 93

    Slide 93 text

    Redux

    Slide 94

    Slide 94 text

    Redux • Inspired by Flux and Elm • Actions, A Store, Reducers • Reducers are pure functions • (state, action) => state • State is read-only • Single source of truth

    Slide 95

    Slide 95 text

    Reducer Component Reducer Component Store messages: [‘hello’] filter: ALL type: ADD_MESSAGE text: ‘hoge’ messages => messages.concat(action.text) filter => action.filter Action type: FILTER text: UNREAD Action Reduce Reduce subscribe

    Slide 96

    Slide 96 text

    import { createStore } from 'redux'; // Reducer function counter(state = 0, action) { switch (action.type) { case 'INCREMENT': return state + 1; case 'DECREMENT': return state - 1; default: return state; } } const store = createStore(counter); const unsubscribe = store.subscribe(() => console.log(store.getState())); store.dispatch({ type: 'INCREMENT' }); // 1 store.dispatch({ type: 'INCREMENT' }); // 2 store.dispatch({ type: 'DECREMENT' }); // 1 unsubscribe();

    Slide 97

    Slide 97 text

    Conclusion

    Slide 98

    Slide 98 text

    Combination simple parts

    Slide 99

    Slide 99 text

    Unix philosophy • Small is beautiful. • Make each program do one thing well. • Build a prototype as soon as possible. • Choose portability over efficiency. • Store data in flat text files. • Use software leverage to your advantage. • Use shell scripts to increase leverage and portability. • Avoid captive user interfaces. • Make every program a Filter.

    Slide 100

    Slide 100 text

    cat access.log | cut -d: -f2 | sort | uniq -c

    Slide 101

    Slide 101 text

    data | your program | your program | output

    Slide 102

    Slide 102 text

    Thank you!