Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Universal JavaScript

Universal JavaScript

Roppongi.rb #3 Rails x Frontend-Tech

Koutarou Chikuba

May 31, 2017
Tweet

More Decks by Koutarou Chikuba

Other Decks in Technology

Transcript

  1. About Me • ϑϩϯτΤϯυ/SPA/Node.js ΤϯδχΞ • ήʔϜܥ => ڭҭܥ =>

    Increments(Qiita) • 4݄͔ΒϑϦʔϥϯεͰ Redux ΍ Express middleware • ࠷ۙͷڵຯ: ReactNative / AMP / ےτϨ
  2. લఏ: ͳͥ Sprockets ͸ࢮ͵΂͖͔ • Ϟδϡʔϧղܾʹ͸ ES Modules ͱ͍͏ඪ४ ͕͋Δ

    • JSͰϑΝΠϧείʔϓΛ࣋ͯͣ ࢀর͕άϩʔόϧ౉͠ ʹͳΔ • ධՁॱͷ੍ޚ͕೉͍͠ • RailsଆʹӅṭ͞Εͯͯ node πʔϧνΣΠϯΛ࢖͍ʹ͍͘ • ஗͍ (ExecJS)
  3. (2015೥౰࣌ͷ) Sprockets ͷࡴ͠ํ • browserify-rails ͷಋೖ, ޙʹ webpack • εΫϦϓτॻ͍ͯ

    sprockets/require Λ commonjs ʹ • άϩʔόϧม਺ͷࢀরΛ module.exports = ... ʹ୅ೖ • ࢀরղܾΛάϩʔόϧม਺͔Β require('...') ʹ
  4. after: commonjs // define on render.js module.exports = () =>

    {/* render */} // use const render = require('./render') render()
  5. ʮ࣮ߦίʔυʯ͔Βʮؔ਺Ϟδϡʔϧʯ΁ // Bad document.title = 'foo' // Good // setTitle.js

    export default function setTitle(title) { document.title = title } // runner.js setTitle('foo')
  6. Webpack ͷ໾ׂ • ES Modules ͷόϯυϧ • ֦ுࢠ͝ͱͷ transform •

    ։ൃ࣌ͷ Hot Reload • ࢀরղܾͷ Alias • etc...
  7. ໰୊ҙࣝ: ػೳ͕͋Γׂ͗ͯ͢Ε૭ • JSόϯυϥͷൣᙝΛӽ͍͑ͯͯ node.js Ͱ࠶ݱͰ͖ͳ͍ • ઃఆϑΝΠϧ͕Ͱ͔͍ & Α͘Θ͔ΒΜ

    • css-modules ಋೖ͕ࠇຐज़Ͱਏ͍ • ίϐϖͰಈ͍ͨޙɺಈ͔ͳ͘ͳͬͨͱ͖ͷௐ͕ࠪେม
  8. Universal JavaScript • Universal: ECMAScript ͷ Spec Λຬͨͤ͹ɺͲΜͳ؀ ڥͰ΋ಈ͘JS •

    Isomorphic : ڱٛͷUniversalɻBrowser/Node͕ର৅ɻ => Webpack ͸ Universal ੑΛഁյ͢Δ(͠΍͍͢)͔ΒϞδ ϡϥϦςΟ͕௿Լ͢ΔΑͱ͍͏࿩
  9. Babel ͸ Universal ͔ʁ • DOM Λ৮Βͣɺbabel-preset-es201* Λ࢖ͬͯΔ͏ͪ͸ Yes •

    ͨͩ͠ ES Modules ͷύεղܾ͸ commonjs + α • lib/index ͱ͔ node_modules ͱ͔ • stage0~3, jsx, flow ͸ඪ४֎
  10. ES Moduls in Browser <script type="module"> import {addTextToBody} from './utils.js';

    addTextToBody('Modules are pretty cool.'); </script> https://jakearchibald.com/2017/es-modules-in- browsers/
  11. ES Modules: ࠓޙͷ༧૝ • དྷ೥ʹ͸࣮૷͕ग़ἧ͏ • ࠷ॳ͸ Fastly ͷΑ͏ͳ CDN

    Ͱղܾ͞ΕΔͷͰ͸ • কདྷతʹ͸ nginx/h2o ͷϞδϡʔϧԽ͞Εͯ࢖͑ΔΑ͏ʹͳ ͬͯΔ͸ͣ • ES Modules ͷ੩తղੳεςοϓ͸ඞཁ ϓϩμΫγϣϯͰ࢖͑Δͷ͸ɺ͓ͦΒ͘ 2~3೥ޙ
  12. Webpack ͷ໰୊ͱࢮ͵ཧ༝: ·ͱΊ • ศརͳׂΕ૭ • Universal ੑΛഁյ͠ίʔυͷϞδϡϥϦςΟ͕௿Լ • ωΠςΟϒͷ

    ES Modules Ͱ૬ରతʹॏཁੑ͕௿Լ δϯΫεతʹ͸ɺDHH͕બΜͩϑϩϯτͷπʔϧ͸ࢮ͵