One Day, you decide to download a
React project
A True Story
import { member as alias } from "Whatever";
import { member1 , member2 } from "Some thing";
[...iterableObj, 4, 5, 6]
myFunction(...iterableObj);
(param1, param2, ...rest) => { statements }
(param1 = defaultValue1, param2, …, paramN = defaultValueN) => { statements }
() => () => () => () =>
import Api from '...'
// worker Saga: will be fired on USER_FETCH_REQUESTED actions
function* fetchUser(action) {
try {
const user = yield call(Api.fetchUser, action.payload.userId);
yield put({type: "USER_FETCH_SUCCEEDED", user: user});
} catch (e) {
yield put({type: "USER_FETCH_FAILED", message: e.message});
}
}
const store = configureStore()
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
{
entry: {
page1: "./page1",
page2: ["./entry1", "./entry2"]
},
output: {
// Make sure to use [name] or [id] in output.filename
// when using multiple entry points
filename: "[name].bundle.js",
chunkFilename: "[id].bundle.js"
}
}
I CANT WAIT TO GET STARTED!!!!!
And your moment of 'non'-clarity....
Its not just React.
Its like...all of it.
Symptoms
- Anxiety
- Yelling at kids on your lawn
- Talking about "the good old days of jQuery"
Diagnosis
Javascript Fatigue
Prescription
- Write a medium post
- Tweet
- Cowbell
It appears that
Javascript's doin a
NEW THANG
...and it needs to chill the **** out.
You Remember the old ways.
And then they went and broke Javascript again, remember?
And again...
Now its time
to meet
So Billy, You're the leader of the gang
How do you keep all your
Javascript together so the apps keep flowin'?
... and Flowin'..?
You gotta know your modules.
Theres 5 to keep in mind
- AMD
- CommonJS
- ES2015
- The 'IIFE'
- UMD
define(function () { 'use strict';
var answer = 42;
function main () {
console.log( 'the answer is ' + answer );
}
return main;
});
'use strict';
var answer = 42;
function main () {
console.log( 'the answer is ' + answer );
}
module.exports = main;
var answer = 42;
function main () {
console.log( 'the answer is ' + answer );
}
export default main;
var myBundle = (function () {
'use strict';
var answer = 42;
function main () {
console.log( 'the answer is ' + answer );
}
return main;
}());
AMD
ES2015
CommonJS
IIFE
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.myBundle = factory());
}(this, function () { 'use strict';
var answer = 42;
function main () {
console.log( 'the answer is ' + answer );
}
return main;
}));
UMD
AKA 'Tha SHiM ZoNe'
Text
These Run All Over!
Hot Takes: You Gotta Know your Pipeline.
Browserify
Webpack
Chain of responsibility
Uses 'transforms'
Code-first.
some transforms in the package.json
Config File
Uses 'loaders'
Configuration based
var browserify = require('browserify');
var b = browserify();
b.add('./browser/main.js');
b
.transform(rollupify)
.transform(babelify)
.bundle()
.pipe(process.stdout);
module.exports = {
entry'index.js',
output: { path: 'myout.js'}
module: {
loaders: [
{
test: /\.frag$/i,
loader: 'gl-fragment-loader'
},
{
test: /\.json$/,
loader: 'json-loader'
}
]
},
};
Tell us some cool bundlerstuff.
ALL THE JUICY BUNDLER SECRETS. SPILL IT!
TREE SHAKING
Rad Visuals
TREE SHAKING
export function square ( x ) {
return x * x;
}
export function cube ( x ) {
return x * x * x;
}
'use strict';
function cube ( x ) {
return x * x * x;
}
console.log( cube( 5 ) ); // 125
In
OUT
ollup that javascript!
RAD VISUALS
They don't call you "Jimmy Streamboat" for nothing - tell us how you and the gang manage being *ASYNC ?
Theres only so many ways to manage Async in JS, and noone can really decide which is best.
- Promises
- Generators
- Observables
- Events
- Streams
- Callbacks
Higher-Level/ More Abstract
Lower Level
function addThenDO(n1, n2, callback) {
var x = n1+ n2
callback(x);
}
function shout(item){
console.log(item)
}
addThenDO(5, 15, shout); //logs 20
Callback
Event
function shout(){
console.log('you did the thing')
}
thing.on('event', shout)
Streams
function assembleScripts() {
return gulp
.src(configFile)
.pipe(webpack.configure(webpackConfig))
.pipe(webpack.overrides(webpackOptions))
.pipe(webpack.compile())
.pipe(webpack.format(formatOpts))
.pipe(webpack.failAfter(failOpts))
.pipe(gulp.dest(dest));
}
- Stream hints
- Backpressure
- FS
Promises
function readJSON(filename){
return readFile(filename, 'utf8').then(JSON.parse);
}
var something = thing.get('whatever').then(doSomething)
promise.all(thing1, thing2, thing3).then(doSomething);
Generators
Observables
The New Stuff
function *foo() {
yield 1;
yield 2;
yield 3;
yield 4;
yield 5;
return 6;
}
for (var v of foo()) {
console.log( v );
}
// 1 2 3 4 5
console.log( v );
Generator do like this:
And is used in
Observables
Used in Rx.js, Angular 2, Cycle.Js
var dragTarget = $('#dragTarget'),
mouseup = dragTarget.onAsObservable('mouseup'),
mousemove = dragTarget.onAsObservable('mousemove'),
mousedown = dragTarget.onAsObservable('mousedown').select(function (event) {
// calculate offsets when mouse down
event.preventDefault();
return {
left: event.clientX - dragTarget.offset().left,
top: event.clientY - dragTarget.offset().top
};
}),
mousedrag = mousedown.selectMany(function (imageOffset) {
return mousemove.select(function (pos) {
// calculate offsets from mouse down to mouse moves
return {
left: pos.clientX - imageOffset.left,
top: pos.clientY - imageOffset.top
};
}).takeUntil(mouseup);
});
mousedrag.subscribe(function (pos) {
// Update position
$('#dragTarget').css({
top: pos.top,
left: pos.left
});
});
Redux Saga
How do you and the gang keep it together, when everyone has their own opinion on
what 'DoIn a nEw THaNg' even is.
- Dotfiles
-Config Files
- CI Files
- Meta Files
{
"bitwise" : true, // true: Prohibit bitwise operators (&, |, ^, etc.)
"camelcase" : false, // true: Identifiers must be in camelCase
"curly" : true, // true: Require {} for every new block or scope
"eqeqeq" : true, // true: Require triple equals (===) for comparison
"forin" : true, // true: Require filtering for..in loops with obj.hasOwnProperty()
"freeze" : true, // true: prohibits overwriting prototypes of native objects such as Array, Date etc.
"immed" : false, // true: Require immediate invocations to be wrapped in parens e.g. `(function () { } ());`
"latedef" : false, // true: Require variables/functions to be defined before being used
"newcap" : false, // true: Require capitalization of all constructor functions e.g. `new F()`
"noarg" : true, // true: Prohibit use of `arguments.caller` and `arguments.callee`
"noempty" : true, // true: Prohibit use of empty blocks
"nonbsp" : true, // true: Prohibit "non-breaking whitespace" characters.
"nonew" : false, // true: Prohibit use of constructors for side-effects (without assignment)
"plusplus" : false, // true: Prohibit use of `++` and `--`
"quotmark" : false, // Quotation mark consistency:
}
Inside a JsHintRC
That's cool, but I'm looking at the .babelrc file, and that's doing something crazy. What is really going on, and what does the future hold?
Ever heard of an AST?
Plato
Complexity Analysis
Esprima
http://esprima.org/
Recast.js
- (require("recast").parse)
- (require("recast").print)
Better living through AST's
Kent Dodds:
What has been the biggest influence on you an the group lately?
Oh that's an easy one....
Functional Programming...
You know, like
Ever Heard of the Lambdas?
The Fat Arrows?
thing.addEventListener("click", function(event) {
var_target = event.target;
this.handleClick(_target);
}.bind(this));
thing.addEventListener("click", (event) => {
let _target = event.target;
this.handleClick(_target);
});
That's a Lambda.
Also, immutability is so hot right now..
I'm talking about PURE functions; no side effect!
function add(num1, num2){
return num1 + num2;
}
add(1, 2) //3
add(1, 2) //3
add(1, 2) //3
var x = 1;
var y = 2;
function add (){
x = x + y;
console.log('somthing', x);
return x;
}
add(); //3
add(); //5
Impure
Pure
So much easier to test!
Splat / Spread
options = _.extend({}, optionsDefault, options);
options = Object.assign({}, optionsDefault, options);
options = {...optionsDefault, ...options}; //new Thang
Freeze
var f = Object.freeze({});
f.bar = 10; //nope. object not extensible.
and many, deep freeze modules on npm...
function removeItem(list, index){
return list.slice(0).concat(list.slice(index + 1))
}
function removeItem(list, index){
return [
...list.slice(0,index),
...list.slice(index+1)
];
} //beep beep. New-Thang Detector is buzzin!
What the future of Javascript?
The future?
Virtual DOMs
Unidirectional Data Patterns
Virtual Doms
Inferno.js is Fire
Virtual Doms
Andre Staltz:
Flux
Redux
Unidirectional Architectures
Elm - MVU
Cycle - MVI
Andre Staltz:
A closer look at some
Next-Level Architecture
MVI
Fully Functional
Reactive
Streams/Observables
const {Observable} = Rx;
const {div, button, p, label, makeDOMDriver} = CycleDOM;
function main(sources) {
const incrementClicks$ = sources.DOM.select('.increment').events('click');
const decrementClicks$ = sources.DOM.select('.decrement').events('click');
const increments$ = incrementClicks$.map(c => 1);
const decrements$ = decrementClicks$.map(c => -1);
const sinks = {
DOM: Observable
.merge(increments$, decrements$)
.startWith(0)
.scan((total, i) => total+i, 0)
.map( total =>
div([
button('.increment', '+1'),
button('.decrement', '-1'),
p(`das counter: ${total}`)
])
)
};
return sinks;
}
Cycle.run(main, { DOM: makeDOMDriver('#app') });
Cycle.js
MotorCycle.js
Questions?
Twitter: @5imian