/images/art2.png

Webpack Overview

webpack is a static module bundler for modern JavaScript applications.

Document: https://webpack.js.org/concepts/

Installation

npm i -D webpack webpack-cli

webpack core concept

Entry

An entry point indicates which module webpack should use to begin building out its internal dependency graph. webpack will figure out which other modules and libraries that entry point depends on (directly and indirectly).

Jest Overview

Jest is a JavaScript Testing Framework

Document: https://jestjs.io/docs/en/getting-started

How to use Jest

function.js

const axios = require('axios');

const functions = {
    add: (num1, num2) => num1 + num2,
    isNull: () => null,
    checkValue: (x) => x,
    createUser: () => {
        const user = { firstName: 'Brad' };
        user['lastName'] = 'Traversy';
        return user;
    },
    fetchUser: () =>
        axios
            .get('https://jsonplaceholder.typicode.com/users/1')
            .then((res) => res.data)
            .catch((err) => 'error'),
};

module.exports = functions;

function.test.js

const functions = require('./functions');

// beforeEach(() => initDatabase());
// afterEach(() => closeDatabase());

// beforeAll(() => initDatabase());
// afterAll(() => closeDatabase());

// const initDatabase = () => console.log('Database Initialized...');
// const closeDatabase = () => console.log('Database Closed...');
const nameCheck = () => console.log('Checking Name....');

describe('Checking Names', () => {
    beforeEach(() => nameCheck());

    test('User is Jeff', () => {
        const user = 'Jeff';
        expect(user).toBe('Jeff');
    });

    test('User is Karen', () => {
        const user = 'Karen';
        expect(user).toBe('Karen');
    });
});

// toBe
test('Adds 2 + 2 to equal 4', () => {
    expect(functions.add(2, 2)).toBe(4);
});

// not
test('Adds 2 + 2 to NOT equal 5', () => {
    expect(functions.add(2, 2)).not.toBe(5);
});

// CHECK FOR TRUTHY & FALSY VALUES
// toBeNull matches only null
// toBeUndefined matches only undefined
// toBeDefined is the opposite of toBeUndefined
// toBeTruthy matches anything that an if statement treats as true
// toBeFalsy matches anything that an if statement treats as false

// toBeNull
test('Should be null', () => {
    expect(functions.isNull()).toBeNull();
});

// toBeFalsy
test('Should be falsy', () => {
    expect(functions.checkValue(undefined)).toBeFalsy();
});

// toEqual
test('User should be Brad Traversy object', () => {
    expect(functions.createUser()).toEqual({
        firstName: 'Brad',
        lastName: 'Traversy',
    });
});

// Less than and greater than
test('Should be under 1600', () => {
    const load1 = 800;
    const load2 = 800;
    expect(load1 + load2).toBeLessThanOrEqual(1600);
});

// Regex
test('There is no I in team', () => {
    expect('team').not.toMatch(/I/i);
});

// Arrays
test('Admin should be in usernames', () => {
    usernames = ['john', 'karen', 'admin'];
    expect(usernames).toContain('admin');
});

// Working with async data

// Promise
// test('User fetched name should be Leanne Graham', () => {
//   expect.assertions(1);
//   return functions.fetchUser().then(data => {
//     expect(data.name).toEqual('Leanne Graham');
//   });
// });

// Async Await
test('User fetched name should be Leanne Graham', async () => {
    expect.assertions(1);
    const data = await functions.fetchUser();
    expect(data.name).toEqual('Leanne Graham');
});

Matchers

Doc: https://jestjs.io/docs/en/using-matchers and https://jestjs.io/docs/en/expect

Redux Overview

Redux Document: English 中文

What is Redux

Redux is a predictable state container for JavaScript apps.

Redux also created by Facebook and it is a improvement from Flux. Redux is state management for any view library (mostly react)

When use Redux

Redux is design for complex UI, multiple view source or many interaction with server. If a simple UI, Redux is not necessary

Workflow

Redux Workflow

Example for Redux core

In index.html

React Posts Archive

How to connect your React app to a backend on the same origin

https://flaviocopes.com/how-to-serve-react-from-same-origin/

React Conditional Rendering

Original source: https://www.robinwieruch.de/conditional-rendering-react

Why We Switched to React Hooks

Original source: https://blog.bitsrc.io/why-we-switched-to-react-hooks-48798c42c7f

Why Can’t I Open My React App By Clicking Index.html?

From My Own Post

How To Use an IntersectionObserver in a React Hook

PDF archive: –>Link<–

Prototype Inheritance in Javascript

Prototype

prototype

Foo.prototype.constructor === Foo; // true
f1.__proto__ === Foo.prototype; // true
f1.constructor === Foo; // true

f1 don’t have constructor, however depends on prototype chain engine will search f1.__proto__. This is line is equivalent to Foo.prototype.constructor === Foo

f1 instantiate a Foo:

Flex and Grid in CSS

Flex

Cheat Sheet provide by CSS-tricks.com

A Flexbox code Example

display

.container {
    display: flex;
}

flex-direction

.container {
    flex-direction: row | row-reverse | column | column-reverse;
}

flex-direction

flex-warp

.container {
    flex-wrap: nowrap | wrap | wrap-reverse;
}

flex-wrap

flex-flow

This is a shorthand for the flex-direction and flex-wrap properties.

Hugo Blog CheatSheet

Create new post

hugo new posts/new.md

Add a picture

  1. Basic markdown

    ![<alt name](< The route start from static folder>)

  2. hugo build-in shortcut –> figure (src is start from static folder)

    \{\{< figure src="" title="" >}}

Documentation of ref and relref

\[Neat](\{\{< ref "blog/neat.md" >}})
\[Who](\{\{< relref "about.md#who" >}})

Theme feature

This theme extended short code. See Theme Documentation - Extended Shortcodes

Http Status Code Overview

Reference: https://www.restapitutorial.com/httpstatuscodes.html

⭐︎ -> “Top 10” HTTP Status Code. More REST service-specific information is contained in the entry.

1XX Information

  • 100 continue – Client should continue
  • 101 switching protocols
  • 102 processing (webDAV)

2XX Success

  • ⭐︎200 OK – The request has succeeded.

    General status code. Most common code used to indicate success.

  • ⭐︎201 Created – A new resource has been created and should return a URI.

    Successful creation occurred (via either POST or PUT). Set the Location header to contain a link to the newly-created resource (on POST). Response body content may or may not be present.

HTML5 Overview 🏗

table

table
├── thead
│   └── tr
│       └── th
├── tbody
│   └── tr
│       └── td
└── tfoot
    └── tr
        └── td

Intersection Observer API

const option = {
    root: null,
    rootMargin: '0px',
    threshold: 0.7, // or an array [0.1, 0.2, ...]
};

const callback = (entries, observer) => {
    entries.forEach((entry) => {
        // Each entry describes an intersection change for one observed
        // target element:
        //   entry.boundingClientRect
        //   entry.intersectionRatio
        //   entry.intersectionRect
        //   entry.isIntersecting
        //   entry.rootBounds
        //   entry.target
        //   entry.time
    });
};
const observer = new IntersectionObserver(callBack, option);

observer.observer(nodeOne); //observing only nodeOne
observer.observer(nodeTwo); //observing both nodeOne and nodeTwo
observer.unobserve(nodeOne); //observing only nodeTwo
observer.disconnect(); //not observing any node

When node fulfilled observer option, callback function will run directly