Hello
I am some text
for Large JS Application
www.thatJSdude.com
(youtube.com/user/khanLearning)
//salute.js
var mySalute = 'Hello';
//app.js
var result = mySalute + ' world!';
//salute.js
var mySalute = 'Hello';
module.exports = mySalute;
//app.js
var mySalute = require('./salute');
var Result = mySalute + 'world!';
//salute.js
module.exports = function(){
return 'Hello JS';
};
//app.js
var salute = require('./salute');
console.log(salute());
//salute.js
module.exports = {
foo:'Hello JS',
bar:'Beer JS'
};
//salute.js
module.exports.foo = 'Hello JS';
module.exports.bar = 'Beer JS';
//app.js
var salute = require('./salute');
console.log(salute.foo);
console.log(salute.bar);
//bar.js
var privateBar = 'Bar';
var bar = privateBar + ' is not so far!';
module.exports = bar;
//foo.js
var bar = require( './bar' );
exports.foo = function(){
return 'Hello ' + bar;
}
//app.js
var foo = require('./foo');
console.log(foo());
// library.js
function square(x) {
return x * x;
}
export function cube(x) {
return x * x * x;
}
export function doubleSquare(x) {
return square(x) * square(x);
}
//or
export { cube, doubleSquare };
import { cube, doubleSquare } from 'library';
console.log(cube(4)); // 64
// export a named variable
export var x = 42;
// export a named function
export function foo() {};
// export the default export
export default 42;
// export the default export as a function
export default function foo() {};
//export an export from another module
export { encrypt as en } from 'crypto';
//export all exports from another module
export * from 'crypto';
// import a module without any import bindings
import 'jquery';
// import the default export of a module
import $ from 'jquery';
// import a named export of a module
import { $ } from 'jquery';
// import a named export to a different name
import { $ as jQuery } from 'jquery';
import * as myModule from "my-module";
import {foo, bar} from "my-module";
import {reallyReallyLongModuleMemberName as shortName, anotherLongModuleName as short} from "my-module";
//commonJS
exports.someMethod = function() {
};
exports.another = {};
//es6
export function someMethod() {
}
export var another = {};
Scripts | Modules | |
---|---|---|
HTML element | <script> |
<script type="module"> |
Top-level variables | global | local to module |
Value of this at top level |
window |
undefined |
Executed | synchronously | asynchronously |
Declarative imports (import statement) |
no | yes |
Programmatic imports (Promise-based API) | yes | yes |
npm install webpack -g
webpack app.js bundle.js
npm install css-loader style-loader
module.exports = {
entry: "./app.js",
output: {
path: __dirname,
filename: "bundle.js"
},
module: {
loaders: [
{ test: /\.css$/, loader: "style!css" }
]
}
};
webpack
//for production
webpack -p
//for continuous incremental
webpack --watch
if (window.location.pathname === '/feed') {
require.ensure(['./feedCore'], function() {
// when this function is called, the module is guaranteed
// to be synchronously available.
require('./feed').show();
});
} else if (window.location.pathname === '/profile') {
require.ensure(['./profileCore'], function() {
require('./profile').show();
});
}
function createGreeting(name, location, age) {
let greeting;
if (location === 'Mexico') {
greeting = '!Hola';
} else {
greeting = 'Hello';
}
greeting += ' ' + name.toUpperCase() + '! ';
greeting += 'You are ' + age + ' years old.';
return greeting;
}
function getBeginning(location) {
if (location === 'Mexico') {
return '¡Hola';
} else {
return 'Hello';
}
}
function getMiddle(name) {
return ' ' + name.toUpperCase() + '! ';
}
function getEnd(age) {
return 'You are ' + age + ' years old.';
}
function createGreeting(name, location, age) {
return getBeginning(location) + getMiddle(name) + getEnd(age);
}
function mouseOnLeftSide(mouseX) {
return mouseX < window.innerWidth / 2;
}
function square(x) {
return x * x;
}
function squareThemAll(items){
return items.map(square);
}
describe("A spec using beforeEach and afterEach", function() {
var foo = 0;
beforeEach(function() {
foo += 1;
});
afterEach(function() {
foo = 0;
});
it("is just a function, so it can contain any code", function() {
expect(foo).toEqual(1);
});
it("can have more than one expectation", function() {
expect(foo).toEqual(1);
expect(true).toEqual(true);
});
});
Hello
I am some text
Does html support block level links?
Does the HTML above trigger a http request when the page first loads ?
Does the HTML above trigger a http request when the page first loads?
4 + 3 + 2 + "1"
Does main1.css have to be downloaded and parsed before main2.css can be fetched?
Paragraph 1
Paragraph 2
Does main2.css have to be downloaded and parsed before Paragraph 1 is rendered on the page?
var foo = function bar() {};
alert(typeof bar);
var arr = [];
arr[0] = 'a';
arr[1] = 'b';
arr.foo = 'c';
alert(arr.length);
myThings.setData({ x: 1 }, true);
What is the menaing of true?
myThings.mergeData({ x: 1 });
// Support Opera Mini, which returns NaN for undefined minlength
if(isNaN(value)){
value = undefined;
}
jquery source code
// Support Opera Mini, which returns NaN for undefined minlength
var isNaNForUndefined = isNaN(value);
if (isNaNForUndefined) {
value = undefined;
}
var elapsedTimeInDays;
var description;
var god_damn_its_IE;
var $d; //elapsed time in days
var dsc; //description
var f_IE;
//When I wrote this, only God and I understood what I was doing
//Now, God only knows
function chartNumber(value){
var power = Math.floor(Math.log10(value));
var fraction = value/Math.pow(10, power);
var ceilFraction = Math.ceil(fraction *2)/2;
return ceilFraction * Math.pow(10, power);
}
// bad
let i, len, dragonball,
items = getItems(),
goSportsTeam = true;
// bad
let i;
const items = getItems();
let dragonball;
const goSportsTeam = true;
let len;
// good
const goSportsTeam = true;
const items = getItems();
let dragonball;
let i;
let length;
// bad
const foo = function () {
};
// good
function foo() {
}
// bad
function concatenateAll() {
const args = Array.prototype.slice.call(arguments);
return args.join('');
}
// good
function concatenateAll(...args) {
return args.join('');
}
// bad
function f1(obj) {
obj.key = 1;
};
// good
function f2(obj) {
const key = Object.prototype.hasOwnProperty.call(obj, 'key') ? obj.key : 1;
};
var evens = [2,4,6];
//es5
var odds = evens.map(function(item){
return item + 1;
})
var pair = evens.map(function(item){
return {
even: item,
odd: item + 1
}
});
//es6
var odds = evens.map(v => v + 1);
var pairs = evens.map(v => ({even: v, odd: v + 1}));
// bad
[1, 2, 3].map(function (x) {
const y = x + 1;
return x * y;
});
// good
[1, 2, 3].map((x) => {
const y = x + 1;
return x * y;
});
Things could be clever, but code doesn't have to
// Magic. Do not touch.
function magic(x){
return x >> 0;
}
//be generous
return Math.floor(x);
const plus1 = a => a + 1;
const mult2 = a => a * 2;
// little confusing
mult2(plus1(5)); // => 12
// bad
return x === 0 ? 'red' : x === 1 ? 'green' : 'blue';
// ok
if (x === 0) {
return 'red';
} else if (x === 1) {
return 'green';
} else {
return 'blue';
}
// good
switch (x) {
case 0:
return 'red';
case 1:
return 'green';
default:
return 'blue';
}
//You are not meant to understand this
const arr = [1, 2, 3, 4];
const len = arr.length;
var i = -1;
var result = [];
while (++i < len) {
var n = arr[i];
if (n % 2 > 0) continue;
result.push(n * n);
}
const isEven = n => n % 2 == 0;
const square = n => n * n;
const result = arr.filter(isEven).map(square);
// no comments for you
// it was hard to write
// so it should be hard to read
const sum = arr => {
var sum = 0;
var i = -1;
for (;arr[++i];) {
sum += arr[i];
}
return sum;
};
sum([1, 2, 3]); // => 6
const sum = arr =>
arr.reduce((x, y) => x + y);
sum([1, 2, 3]); // => 6
// bad
// I have to find a different job
var _ = require("underscore");
_.compact(["foo", 0]));
_.unique(["foo", "foo"]);
_.union(["foo"], ["bar"], ["foo"]);
// good
//thank god, i survived
const compact = arr => arr.filter(el => el);
const unique = arr => [...Set(arr)];
const union = (...arr) => unique([].concat(...arr));
compact(["foo", 0]);
unique(["foo", "foo"]);
union(["foo"], ["bar"], ["foo"]);
//
// Dear maintainer:
//
// Once you are done trying to 'optimize' this routine,
// and have realized what a terrible mistake that was,
// please increment the following counter as a warning
// to the next guy:
//
// total_hours_wasted_here = 42
Pressing tab after /**
Writing good code is hard and reproducing client-side errors is even harder
window.onerror = function(message, source, lineno, colno, error) {
var req = new XMLHttpRequest();
var params = 'msg='' + encodeURIComponent(msg) +
'&url=' + encodeURIComponent(url) +
'&line='' + line;
req.open('POST', '/scripts/logerror.php');
req.send(params);
}
//convert to JS Date oboject from yyyymmdd
function parseDate (dateString){
var match = dateString.match(/(\d{4})(\d{2})(\d{2})/);
var formattedDate = match[2] + '/' + match[3] + '/' + match[1];
return new Date(formattedDate);
}
//contianer.sass
@import 'stylesheets/config/colors'
.container
background: $blue
//header.sass
@import 'stylesheets/config/colors'
.header
font-weight: bold
font-size: 3em
color: $red
//footer.sass
.footer
font-style: italic
//webpack-css-example
npm install
npm run build
Take a look at the generated CSS in build/
/*app.css*/
html {
font-family: sans-serif; }
.header {
font-weight: bold;
font-size: 3em;
color: #f00; }
.u-clearfix {
overflow: hidden; }
.footer {
font-style: italic; }
.container {
background: steelblue; }
Press B
“ As a developer our job is to promise quality code at the beginning of the project and somehow mess it up in six months.”
www.thatJSdude.com
(youtube.com/user/khanLearning)