Catatan Belajar Webpack

Free $20 Linode Cloud hosting Coupon, register at  Free Linode Cloud Hosting

(Coupon $20 available at Linode $.20 Coupon ) 👍🏿

Apa itu webpack?

Webpack adalah tools untuk membundle modul-modul Javascript. Jika Anda mulai serius untuk membangun aplikasi HTML 5 – Javascript hingga skala besar tools ini akan sangat membantu. Anda dapat mengelola source code Javascript Anda yg kompleks, lalu membundlenya menjadi satu kesatuan file yg mudah di include ke dalam file HTML Anda. Dengan menggunakan webpack, maka Anda diperbolehkan melakukan include antara file JS dengan perintah require seperti di NodeJS dan membangun modul JS untuk dapat dipakai reusable keluar lingkup file JS lain dengan perintah module.exports yg juga sama seperti di NodeJS. Lalu setelah source code Anda selesai ditulis maka Anda dapat membundle keseluruhan file JS Anda menjadi sebuah file JS yg dapat dengan mudah diintegrasikan ke dokumen HTML.

Sumber: qaiserlab

 

Instalasi dan Persiapan Dasar

1.prepare-folder
mkdir webpack-demo
2.init-project
npm init -y
3.save-webpack-locally
npm install webpack –save-dev (install Webpack locally)
4.create-basic-files
Created files and folders, isi ketiga files disini

Install Babel, ES6 transpiller dkk (locally)

5.install-babel
Install kelengkapan
6.npm-start1
Sekarang kita punya npm start dan npm build
6.npm-start2
folder dist dan file bundle.js dibuat oleh webpack saat npm start

Run Dev server dan Cek di Browser

9.run1
Development server
9.run2
Output di Browser

 run npm run build to compile our bundle in production mode with UglifyJS

 

Menggunakan Javascript Modules dengan Webpack

Contoh kasus: lodash

npm install lodash --save

10.isntall-lodash.png

touch ./src/people.js

Yang berisi:

// src/people.js
const people = [{
  manager: 'Jen',
  name: 'Bob'
}, {
  manager: 'Jen',
  name: 'Sue'
}, {
  manager: 'Bob',
  name: 'Shirley'
}, {
  manager: 'Bob',
  name: 'Terrence'
}]

export default people

1 // src/app.js
2 import {groupBy} from ‘lodash/collection’
3 import people from ‘./people’
4
5 const managerGroups = groupBy(people, ‘manager’)
6
7 const root = document.querySelector(‘#root’)
8
9 root.innerHTML = `Heello! <br /> <pre>${JSON.stringify(managerGroups, null, 2)}</pre>`

 

11.build-watch-bareng.png
webpack –watch dan webpack-dev-server jalan bersama

Loaders

Loaders adalah

Contoh loaders:

  1. sass-loader transforms Sass into CSS.
  2. css-loader parses the CSS into JavaScript and resolves any dependencies.
  3. style-loader outputs our CSS into a <style> tag in the document.
12.loaders-es6.png
Loaders untuk babel yang merubah es6 ke es5

Mari kita coba semua loaders yang ada diatas

npm install css-loader style-loader sass-loader node-sass --save-dev

13.install-loader

 touch ./src/style.scss
 import './style.scss' // di app.js

12.scss1.png

13.new-rules
new rules in  webpack.config.js

Contoh Loader File

app.js


import codeURL from './code.png'
const img = document.createElement('img')
img.src = codeURL
img.style.backgroundColor = "#2B3A42"
img.style.padding = "20px"

16.img-file-loader
Gambar di load ssebagai base64

Membuat CSS terpisan dari file CSS

Sebelumnya kode CSS berada disini:

 

 

 

17.css-difile-ygsama
CSS ada di head
18.extract-text.png
npm install extract-text-webpack-plugin@2.0.0-beta.4 --save-dev

12.load-css12.load-css2

Tambahkan <link rel=”stylesheet” href=”dist/app_bundle.css”> di index.html

 

 

 

Sumber

  1. https://www.sitepoint.com/beginners-guide-to-webpack-2-and-module-bundling/
  2. http://qaiserlab.com/2017/04/tutorial-cara-menggunakan-webpack
Advertisements

Catatan belajar Framework frontend JS Vue

Free $20 Linode Cloud hosting Coupon, register at  Free Linode Cloud Hosting

(Coupon $20 available at Linode $.20 Coupon ) 👍🏿

Post ini dimaksudkan sebagai catatan pribadi saya dalam belajar Vue.js, saya catat disini karena saya pelupa dan kadang baru ingat setelah Google justru mengarahkan saya ke Blog saya sendiri saat saya mencari sesuatu, kadang baru ngeuh “oh iya saya pernah belajar ini dulu”.

Untuk catatan lain yang tidak menggunakan build tool buka disini: link

Instalasi (link)

1.Install-cli
npm install –global vue-cli
2.test-vue-cli
vue
3.webpack-init1
vue init webpack my-project
3.webpack-init2
Lanjutan vue init webpack my-project
4.get-in
Hasil dari: vue init webpack my-project
5.NPM-Install
npm install
6.NPM-run
npm run dev
7.The-Website
localhost

 

Setup VIM

8.vim-vue-support1
vim .vimrc
8.vim-vue-support2
au BufReadPost *.vue set syntax=html

Create Simple Hello World

11-Hello-files12.HelloWorlds12.HelloWorldsMainJS13.REsult

Create Simple Component

 

16.Instance-with-component-index2
Browser Output

Event Method pada Component

17.methods-pada-components
Event pada vue component

Data Variables dalam Component

18.compoinent-data
Most of the options that can be passed into the Vue constructor can be used in a component, with one special case: data must be a function.

Computed Variable

17.var-computed

Instead of a computed property, we can define the same function as a method instead. For the end result, the two approaches are indeed exactly the same. However, the difference is that computed properties are cached based on their dependencies. A computed property will only re-evaluate when some of its dependencies have changed.

Variable Watcher dalam Component

19.compoinent-watcher
Setiap ada perubahan terdeteksi counter akan bertambah

Style Binding / Kondisi pada Pemberian Class

20.style-binding1
active dan text-danger muncul dari kondisi variable setelahnya
 Cara lain yang lebih pendek (output sama dengan diatas)
Opsi lain

21.style-binding3

Pada componen

<hellow v-bind:pesan=”pesan” v-bind:class=”classObject”></hellow>

Hasilnya komponen pembungkus template akan seperti ini

<span class=”active text-danger”> . . .

Condition

  1. v-if
  2. v-else

Loop

  1. v-for array objects
  2. v-for pada fields
  3. v-for dengan index, key dan value

Miscellenous

  1. Filter data
  2. Add new data record
  3. Delete record from data
  4. Sample ToDo
  5. Property “is” dan “href” pada component
  6. Property “is” dan “src” pada component image
  7. Methods and computed

Form Input

  1. Text input
  2. Checkbox input
  3. Radio Picker
  4. Select input
  5. Multiple Select
  6. Select rendered options
  7. Selected rendered options set value

Components

  1. Component for, Bind dan Is
  2. Pass text sebagai html property
  3. Component props camelCase
  4. Bind input text value ke component
  5. Trigger event dengan $emit
  6. Template component membaca data dalam component
  7. Template dengan text/x-template
  8. v-once untuk cache static content

Transition effects

  1. Transition dan Callback
  2. Postponed

Mixin

  1. Simple sample
  2. Mixins Methods
  3. Global Mixins

Custom Directive

Vue.directive

  1. Simple sample, set-focus directive
  2. Directive callbacks/Hook Function
  3. Hook Arguments
  4. Passing Object 

Render Function

  1. Basic Component
  2. x-template
  3. render template and v-for

Catatan sederhana belajar Vue Tanpa Build Tools

Pada catatan ini berisi snaphot belajar VueJS dari website Resminya tanpa menggunakan Build Tool apapun.

Declarative Rendering

Template Saja

1.NothingHappen
Tidak ada yang di-render

Template dan Vue Instance

1.somethingHappen
Angka dirender dibrowser apa danya
1.somethingHappen2
Penambahan

 

 

Variable Data

2.Apakabar-dunia
Mencetak isi variable pesan ke template

2.Apakabar-dunia3

 

 

2.Apakabar-dunia4
Kondisi, Jika true maka munculkan
3.looping
Looping

Menangani Input Data

4.inputtext
Input data dengan v-model

Menangani Method dan click event

4.inputtext2

Membuat dan menggunakan Komponen

5.component-tag

Mengirim Variable Ke Component

5.component-tag2.png
<figura-foto v-bind:url=”url” > </figura-foto>

Array untuk loop Component

5.component-loop.png
Tiga gambar ditampilkan oleh Component yang sama

Callback untuk perubahan dengan watch

6.callback
vm.$watch untuk properti lain cek  API reference

Abaikan Perubahan data Dengan one-time interpolations

14.freeze-model
Perubahan pada input tidak merubah/render ulang

HTML Text

15.htmlmode

Directives

Directive adalah semua yang diawali oleh v-

contohnya:

<p v-if="seen">Now you see me</p>

Computed dan Watcher

Watcher

8.watcher

Computed

7.computed.png

 Setter dan Getter Untuk Computed

// ...
computed: {
  fullName: {
    // getter
    get: function () {
      return this.firstName + ' ' + this.lastName
    },
    // setter
    set: function (newValue) {
      var names = newValue.split(' ')
      this.firstName = names[0]
      this.lastName = names[names.length - 1]
    }
  }
}

 

Selesai

Slackbot Using Javascript

Simple Slack Bot using JavaScript

*This post is not a tutorial, it’s intended for my personal note only.

Github

Basic knowledge about Slack Bot

  1. Basic use
    • Sample, a simple bot Reminder
    • /remind me Enjoy your life in Everyday/remind me Enjoy your life in Everyday2.sample2
  2. Slack API
    1. Create slack app3.createApp.png
    2. Manage slack app Screenshot from 2017-12-06 09:09:22
    3. API Token and Creadential
      5.Credential
      This is just a Sample App so I let you know the credential.

      Client ID: 281615142867.282451969317; Client Secret : a4071bfc70147832db46ba3844f85dff; Verification Token : Cv0JeOtgy0Dlh3T20zFWySHQ

    4. Your Slack App is ready to connect
  3. Comprehensive Introduction
  4. Sample Slackbot With Firebase
    1. Go to Google Cloud Console
    2. Create Google Cloud Project KrimiBotak (Of course we need a server)8.Create-GC-pROJECT9.Project-Created
    3. Setup App Engine
      10.SetupAppEngine
      Choose NodeJS and then pick a wanted server location

      12.project-created-follow-the-guide.png

    4. Follow the step-by-step GAE tutorial15.CONFIRM-PROJECT16.GOOGLE-CLOUD-SHELL17.clone-hello19.repo
      19.install-anrun
      install, set port and run the sample App

      20.web-preview

      22.Hello-word-is-running
      Hello Word on NodeJS Google App Engine

      22.deploy-appengine.png

      • If you got an error on deployment then you just need to run following command:
      • gcloud config set app/use_deprecated_preparation True21. Deploy-app.png

        25.running-app
        App Deployed on Google App Engine
    5. Go to Firebase console7.FIREBASE-CONSOLE13.CreateFirebaseProject14.add-project14.firebase-dashboar.png
    6. Firebase is ready now
    7. Test Firebase database / endpoint101.DatabaseFirebase103.set_node

      104.set-rules-to-public
      Set Public Enpoint
    8. Test endpoint access using POSTMAN105.postman1104.update
    9. Firebase database seems working properly
  5. Next setup NodeJS on my local machine

NodeJS Express Basic Tutorial

Setting up a Node (Express) development environment

Requirement

110.App-ENgine-Version
App Engine Shell
123.local-env
My Local Env

 

  1. Install NodeJS link
  2. Update NodeJS link
  3. Install NPM5 link

Create Project

  1. First create a directory for your new application and navigate into it:
    • mkdir krimibotak
      cd krimibotak
  2. Generate Project
    • npm init
  3. Install express js
    • npm install express --save
  4. package.json
    • 127.package.jsom
  5. *change index.js to app.js
  6. 125.app-run.png
    Masukkan keterangan
  7. Add Firebase
    • npm install --save firebase
      
  8. So far everything goes well, let’s learn to create RestAPI Using ExpressJS to warming up.
  9. Adjustment For Google App Engine

    1.modification-for-GAE
    new app.yml and modified app.js
    1.modification-for-GAE2
    app.js

    1.modification-for-GAE3
    app.yaml
  10. Deploy
    • gcloud app deploy –project krimibotak
  11. Create Simple Rest API

  12. Create api folder and some js files to start learning about basic functionality of ExpressJS Restful API development.
    • mkdir api && mkdir api/controllers api/models api/routes
    • touch api/controllers/testController.js api/models/testModel.js api/routes/testRoutes.js
    • 1.api-folder
      Sample API files (Not an Unit Test Files)
  13. Install nodemon
    • npm install –save-dev nodemon
    • npm install -g nodemon (we need it globally )

      103.nodemon-in-action
      Nodemon in action
  14. Install body-parser
    • npm install –save body-parser
  15. Current js files now are following:
    2.app-js
    app.js
    3.routes-js
    testRoutes.js
    4.controller
    testController.js

    201-basic-api201-basic-api2

  16. Setting up Firebase Database

    202-Firebase-DB-Connect-test
    Testing Firebase Realtime DB Connection
  17. Install firebase-tools for shell support
    npm install -g firebase-tools
  18. Menjalankan Server Web Lokal untuk Pengembangan
    firebase init
    110.firebase-ini
    105.database-connect
    firebase serve
    105.ups-Firebase-is-Error
    ups Firebase is Error
    199-noneed.png
    Remove all unwanted files

    107-movefirebase-to-controller
    Move all firebase from app.js to testController.js
  19. CRUD with Firebase Realtime Database
    129-header
    Required to post raw data
    161.empty-firebase
    Empty collection
    162.Firebase-first.png
    Create
    163.create-again
    Create again
    164.updated-cat
    Update a record
    165.read-cat.png
    Get a record

    166.deleted.png
    Delete
  20. Firebase is successfully tested.

Let’s start create the bot using this following documentation

link: https://get.slack.help/hc/en-us/articles/115005265703-Create-a-bot-for-your-workspace

Bot Name: krimibot

The Slack channel: https://kodinkanlah.slack.com/

  1. https://kodinkanlah.slack.com/apps/A0F7YS25R-bots
  2. 300
  3. 301
  4. 304

    306
    Please refer to our bot user API documentation, which tells you everything you need to know about setting up a bot integration.
  5. Our Gol is: Post messages and react to members307
  6. Node Library for the Slack APIs
    • $ npm install @slack/client –save
    • 309
  7. Slack Developer Kit for Node.js
    1. Try to send message to General  with WebApi320-send-to-chan-general305.png
  8. Start Bot309-bot-started.png
    401-the-krimi-bot
    Bot should be in a channel to work
    303-nochanel.png
    Native message
    304-mention-krimibot
    Mention the bot then “Invite them to join”
    303-invited
    Bot joined the general channel
    303-Greeting-from-Bot.png
    Greeting message from bot
    303-receive-message-from-channel
    Receives messages from Channel
    303-thanks-detection.png
    Thank / Karma detection
    304-max-karma-pont.png
    Everyone has 5 karma points to give out per day.

    304-sent-karma.png
    Firebase Realtime Database
  9. To be continue…

 

 

 

Urls:

  1. https://get.slack.help/hc/en-us/articles/115005265703-Create-a-bot-for-your-workspace
  2. Bot Info Page
  3. https://api.slack.com/bot-users
  4. https://slackapi.github.io/node-slack-sdk/bots#receiving-messages

Olahraga Untuk Programmer dan Orang Kantoran

Duduk 8 jam perhari dan berjibaku dengan berbagai rutinitas kerja merupakan hal yang dapat menjenuhkan dan kejenuhan tersebut lama kelamaan menjadi bibit-bibit stress yang dapat menurunkan performa kerja, menambah rasa malas/jenuh dan pada akhirnya dapat menyebabkan banyak masalah dikantor atau bahkan dapat sampai menyebabkan  kehilangan pekerjaan.

Untuk mencegah hal tersebut saya memiliki tips yang efektif dan terbukti bekerja (setidaknya pada diri saya sendiri) untuk dapat mengurangi rasa jenuh, bosan dan tidak bergairah, cara tersebut adalah memiliki hobi positif yang menyenangkan dimana fikiran kita untuk sementara waktu diistirahatkan dengan dialihkan ke hal lain yang menyenangkan dan tentu saja menyehatkan dalam kasus saya berlatih olahraga beladiri adalah pilihan yang saya pilih, selain menyenangkan berlatih beladiri dapat menjadi pilihan karena akan menambah pergaulan, kesehatan dan kemampuan fisik disamping tentunya memberikan kemampuan kita mempertahankan diri.

Kickboxing dan Muay Thai  adalah beladiri yang memiliki tempat latihan yang cukup mudah untuk di temui di Bandung Jawa barat ini, akan tetapi mencari yang memiliki harga terjangkau dan pelatih yang berkualitas tentunya tidak mudah, semua saya sudah survey dan yang memiliki harga murah dan tetap berkualitas adalah Kickboxing Indonesia (KBI Unit latihan jalan Emong no 19 Bandung), selain pelatih dan tempat latihan yang menyenangkan (ada matras empuk standar Judo juga memiliki peralatan tinju yang lumayan lengkap) lokasinya juga mudah di jangkau karena berada di pusat kota (Jalan Emong no 19 berada di antara jalan Karapitan dan Burangrang yang banyak tempat makan dan nongrongnya).

Pada 3 bulan pertama latihan yang dilatih adalah fokus tinju dan sedikit tendangan kickboxing/Muay Thai setelah itu materi akan menjadi Full Muay Thai dan ditambah dengan materi Clinch, bantingan sanda dan juga MMA yang tentunya kesemua itu bisa didapat tanpa biaya tambahan, hanya dengan membayar 250rb perbulan bisa mendapatkan berbagai materi beladiri dari atlit dan praktisi beladiri yang berpengalaman baik di Bandung maupun di even-event nasional.

Kickboxing Indonesia sendiri adalah perguruan / klub beladiri di Bandung yang menawarkan latihan kickboxing beraliran Muay Thai / Thai Boxing yang dicampur dengan beladiri (kungfu) Sanda, hal ini tidak aneh karena atlit-atlit KBI sendiri berlaga di berbagai event seperti tinju amatir, muay thai amatir, kickboxing amatir dan juga even-event sejenis yang berlevel profesional.

Walau mengajarkan olahraga yang dikenal keras Kickboxing Indonesia (KBI Bandung) tidak menggunakan kekerasan yang tidak perlu dalam berlatih, suasana yang akrab hangat dan penuh rasa kekeluargaan menjadi ciri khas yang paling kental yang dimiliki oleh kickboxing indonesia (KBI Bandung) namun demikian rasa saling menghormati sesama member, pelatih dan antara pelatih dengan member tetap terjaga dengan baik.

Untuk mendapatkan informasi mengenai tempat latihan Muay Thai / Thai Boxing  di Kickboxing Indonesia dapat menghubungi kontak di web berikut: link.

Untuk berlatih beladiri Muay Thai anda cukup mengeluarkan biaya latihan 250rb perbulan dan gratis biaya pendaftaran (serta dapatkan harga khusus untuk atlit berprestasi).

ReactJS: My Getting Started Notes

Main Tools

  • NPM and Yarn
  • Webpack
  • Babel
  • JSX + ES6
  • Flux
  • Guts and Persistence (to avoid giving up or being scared)

 

  1. React JSX at Glance

    REACT-IMG1

    JSX is an XML/HTML-like syntax used by React that extends ECMAScript so that can co-exist with JavaScript/React code. The syntax is intended to be used by preprocessors to transform HTML-like text found in JavaScript files into standard JavaScript objects.

    • JSX needs transpilers like Babel to transform it into ES5 js script (link)
    • React Components are the building blocks of React (Maybe just like an Angular Directive / keep in mind that’s React is only V in MVC cmiiw).
    • React Component as a collection of HTML, CSS, JS, and some internal data specific to that component.
    • React Components can have nested components inside of them.
    • React Virtual DOM is JavaScript representation of the actual DOM.
    • React Life Cycle: 1. Signal to notify our app some data has changed → 2. Re-render virtual DOM → 3. Diff previous virtual DOM with new virtual DOM → 4. Only update real DOM with necessary changes (sample).
    • React Virtual DOM is fast

      whenever setState is called, React creates a new virtual DOM, does the diff, then updates the real DOM

    • Life Cycle explained
      1. componentWillMount: Invoked once before the initial render.
      2. componentDidMount – Invoked once after the initial render.
      3. componentWillReceiveProps – This life cycle is not called on the initial render, but is instead called whenever there is a change to props.
      4. componentWillUnmount – This life cycle is invoked immediately before a component is unmounted from the DOM.
    • for transformation  from JSX to JS, we need to set up some sort of transformation phase as you’re developing with Webpack+Babel.
  2. Flux architecture 2.FLUX-LOGO1

    Flux is an application architecture for React utilizing a unidirectional data flow.

    • Flux unidirectional cycles that data can flow through
    • Flux is a pattern for managing data flow in your application.
    • Flux can  structure and architect React application in an efficient way.
    • Flux is great.But you don’t have to use Flux with React.

      Don’t let the complexity of Flux ruin the simplicity of React.

    • Flux Part (link)
      • Dispatcher
        • Dispatcher is used to broadcast payloads to registered callbacks.
      • Store
        • Holds the data of an application.
      • Action
        • Actions are semantic and descriptive of the action taking place.
      • View
        • Data from stores is displayed in views. Views can use whatever framework you want
    • Flux Flow
      • 1. Views send actions to the dispatcher. → 2. The dispatcher sends actions to every store. → 3. Stores send data to the views.
      • Different phrasing: Views get data from the stores.
        Different phrasing: Views get data from the stores.
    • Flux Sample Application flux-todomvc
      1. $ git clone https://github.com/facebook/flux.git && cd flux
      2. $ yarn install4.install-sample
      3. hmhmhm.. I just realize that ‘git clone https://github.com/facebook/flux.git&#8217; was downloaded all samples applications instead of single todomvc app.
      4. 5.folder-app-structure
      5. Nothing is wrong, lets continue
      6. Add Flux-Shell
      7. $ cp -R examples/flux-shell examples/my-todomvc
      8. 7.new-files
        New Files from flux-shell (my-todomvc is our new flux-todomvc)
      9. $ cd examples/my-todomvc && yarn install9.install
      10. See “Hello world!” on browser (mine is /home/yusuf/test/flux/examples/my-todomvc).10.hellow-world.png
      11. Set up TodoMVC assets
      12. $ cp -R ../todomvc-common todomvc-common
      13. $ vim examples/my-todomvc/index.html (link)
      14. $ vim examples/my-todomvc/src/root.js (link)
      15. $ yarn run watch (under my-todomvc)15.yarn-run-watch
      16. refresh page file:///home/yusuf/test/flux/examples/my-todomvc/index.html

         The page should now have some styling and still say "Hello World!" in the center.
        The page should now have some styling and still say “Hello World!” in the center.
      17. Setting up Flux
        1. Under my-todomvc
        2. $ cd ./src && mkdir ./containers ./data ./views && touch ./containers/AppContainer.js && touch ./data/AppContainer.js ./data/TodoActionTypes.js ./data/TodoDispatcher.js ./data/TodoStore.js && touch ./root.js ./views/AppView.js18.initfiles
        3. Code for files above link
        4. asd
      18. Build
        1. $ yarn build
        2. or $ yarn run build
        3. reload file:///home/yusuf/test/flux/examples/my-todomvc/index.html from browser20.hello-from-flux.png
        4. In case you  are getting following errors while running “yarn run build” or “yarn run watch”:

          ERROR in ./~/flux/utils.js
          Module not found: Error: Cannot resolve ‘file’ or ‘directory’ ./lib/FluxContainer in /home/yusuf/test/flux/examples/my-todomvc/node_modules/flux
          @ ./~/flux/utils.js 10:27-57

          ERROR in ./~/flux/utils.js
          Module not found: Error: Cannot resolve ‘file’ or ‘directory’ ./lib/FluxMixinLegacy in /home/yusuf/test/flux/examples/my-todomvc/node_modules/flux
          @ ./~/flux/utils.js 11:23-55

          ERROR in ./~/flux/utils.js
          Module not found: Error: Cannot resolve ‘file’ or ‘directory’ ./lib/FluxReduceStore in /home/yusuf/test/flux/examples/my-todomvc/node_modules/flux
          @ ./~/flux/utils.js 12:29-61

          ERROR in ./~/flux/utils.js
          Module not found: Error: Cannot resolve ‘file’ or ‘directory’ ./lib/FluxStore in /home/yusuf/test/flux/examples/my-todomvc/node_modules/flux
          @ ./~/flux/utils.js 13:23-49

          ERROR in ./~/flux/index.js
          Module not found: Error: Cannot resolve ‘file’ or ‘directory’ ./lib/Dispatcher in /home/yusuf/test/flux/examples/my-todomvc/node_modules/flux
          @ ./~/flux/index.js 10:28-55

        5. This is how to fix errors above
          1. delete ./node_modules and re-build, is it still error ? try second way
          2. $ yarn add flux

            21.yarn-error1.png
            It will install another missing dependency
        6. $yarn run build   / $ yarn run watch
      19. reload reload file:///home/yusuf/test/flux/examples/my-todomvc/index.html from browser20.hello-from-flux
  3. Reduxredux-react

  4. Persisting  data with server APIs

Setting up Webpack + Babel KONFIGURASI-react-es6-webpack

Webpack gets every module your application needs, then packages all of those modules into one bundle file (if needed — few bundles).

Installation

yarn add webpack --dev

Flag --dev (--save-dev) says that this dependency will be saved in devDependencies in package.json and required only in development.

  • Webpack

    • Webpack is a code bundler. It takes your code, transforms and bundles it.
    • three main things Webpack need to know (basic things to setup).
      1. starting point of your application, or your root of JavaScript file
      2. which transformations to make on your code (SASS to CSS, JSX to JS etc.,)
      3. location it should save the new transformed code.
    • Webpack configurations. Conveniently, this file should be named webpack.config.js
    • webpack.config.js and be located in the root directory of our project.
    • Build example without webpack.config.js
      ./node_modules/.bin/webpack src/index.js dist/bundle.js
    • Build example using webpack.config.js

      Most projects will need a more complex setup, which is why webpack supports a configuration file.

      ./node_modules/.bin/webpack --config webpack.config.js
      
    • Build using npm scriptNPM-SCRIPT
    • webpack terminal commands
      • webpack -w  #watchp
      • webpack -p #minified
    • Webpack vs gulp article
    • Yarn in better NPM article, mgrating from npm to yarn
  • Babel

    Transpilers, or source-to-source compilers, are tools that read source code written in one programming language, and produce the equivalent code in another language. Languages you write that transpiled to JavaScript are often called compile-to-JS languages, and are said to target JavaScript (source).

    In terms of React, Babel is going to allow us to transform our JSX (which you’ll see soon) into actual JavaScript. What’s nice about Babel though is it can be used for much more than just JSX -> JS transformations. You can also opt into “future” versions of JavaScript (ES2015, 2016, etc)

List of transpilers:

Installing Babel

npm install --save-dev babel-core babel-loader babel-preset-react

babel-core is babel itself, babel-loader is the webpack loader we’ll use, and babel-preset-react is to get the JSX -> JS transformation going.

My Steps to the Glorious “Hello World” With ReactJS

HELLO-WORD-REACTJS

  1. $ mkdir blog-hellojs and cd blog-hellojs
  2. $ yarn init
    • 1.yarn-Init
  3. $ yarn add react
  4. $ yarn add react-dom
    1. 4.package.json
    2. Now I have react and react-dom
  5. Now it is time to add babel power to the project
  6. $ yarn add babel-core babel-cli babel-loader babel-preset-es2015 babel-preset-react react-hot-loader –dev (the deps should be under devDependencies instead of dependencies, I made a typo on yarn add command, I wrote -dev instead of dev)
    • 5.install-babel
      check package.json out!
    • 6.test-Babel
      test to run babel using yarn (it’s a magic)
    • Now I have react, react-dom and babel (plus babel required deps for reactjs dev)
  7. Now it is time to add webpack power to the project
  8. $ yarn add webpack webpack-dev-middleware webpack-hot-middleware –dev
    • 7.webpack-json
      Accidentally remove react and react-dom from this file :V
    • The image above is missing react and react-dom, make sure you add that manually by running (somehow I just deleted react and react-dom from it and made error import command):
      • $ yarn add react
      • $ yarn add react-dom
  9. Adding webpack.config.js
    1. Multiple Entry Points
    2. Install uglifyjs-webpack-plugin
      • $ yarn add uglifyjs-webpack-plugin –dev
      • ups, no need to install uglifyjs-webpack-plugin anymore, it’s already in webpack.optimize.UglifyJsPlugin
      • 8.uglify-plugin
    3. $ touch webpack.config.js
    4. $ mkdir ./src
    5. $ touch ./src/index.js    <- ES6 JS(X) entry support
    6. mkdir ./src/assets
    7. $ mkdir ./dist <- public directory where the bundle.js will be placed
    8. $ vim  ./webpack.config.js (development)
    9. vim  ./src/index.js
      • Copy JSX sample code (hello world) from here
    10. Run webpack build using yarn
      1. $ yarn run webpack
      2. wHoAA, I got an Error, fuxk yeah… lets fight!

        ERROR in ./src/index.js
        Module parse failed: /home/yusuf/test/blog-hellojs/src/index.js Unexpected token (5:2)
        You may need an appropriate loader to handle this file type.

        You may need an appropriate loader to handle this file type.
        You may need an appropriate loader to handle this file type. ??????????????
      3. wait… I’m currently Googling right now………………!
      4. Ok, the the problem is because of wrong folder name (I apologize for that, the url https://pastebin.com/edit/nd6N1F2x is updated, so it won’t occur to you for sure :v )
        • in webpack.config.js, change following line:
          • path.resolve(__dirname, ‘app‘) to
          • path.resolve(__dirname, ‘src‘) (actually it was updated from pastebin)
      5. Getting another new error, hmhmh … it looks interesting (I just wanted to smash my laptop right now…)
        1. The next error is………………….. (hmhmhm looks so nasty and stupid!)

          ERROR in ./src/index.js
          Module not found: Error: Can’t resolve ‘react’ in ‘/home/yusuf/test/blog-hellojs/src’
          @ ./src/index.js 3:13-29

          ERROR in ./src/index.js
          Module not found: Error: Can’t resolve ‘react-dom’ in ‘/home/yusuf/test/blog-hellojs/src’
          @ ./src/index.js 7:16-36
          error Command failed with exit code 2.

          error Command failed with exit code 2.
          ERROR in ./src/index.js
        2. The error is still occurring for somehow (even the error is magic) ….
        3. Ladies and Gentlemen …….I’m proudly announce to you that the error is “REACT IS NOT INSTALLED YET”
          • Somehow my prev ‘yarn add react’ and ‘yarn add react-dom’ are not working properly (or I just accidentally removed them from the package.json)
        4. Make sure your /dist/ folder is empty by running following script:
          • $ rm dist/*
        5. Ok now run following code below to transpille the ES6 JSX code from src/index.js to dist/bundle.js
          • $ yarn run webpack
          • yarn run webpack
            yarn run webpack
          • vim dist/bundle.js
            vim dist/bundle.js
        6. Thanks God Babel is working now…
      6. 13.structure-folders
  10. Create HTML File
    • touch ./src/index.html 
    • html code
  11. Install html-webpack-plugin
    $ yarn add html-webpack-plugin --dev
  12.   Update webpack.config.js enable html-webpack-plugin on build
    1. Follow this tutorial to add html-webpack-plugin link
    2. New required line on webpack.config.js on lines 5-10 and 34
      1. 14.config-for-html.png
    3. $ yarn run webpack
      1. 16.index.html.png
      2. Generated ./dist/index.html
        Generated ./dist/index.html
  13. Run server
    1. $ yarn install webpack-dev-server –dev
    2. Add following line to update package.json
    3. "start": "webpack-dev-server"
      • 17.yarn-webpack-run
  14. Run server using
    1. $ yarn start
    2. or $ yarn run start

 

 

Sources:

  1. https://blog.hellojs.org/setting-up-your-react-es6-development-environment-with-webpack-express-and-babel-e2a53994ade
  2. http://tylermcginnis.com/reactjs-tutorial-a-comprehensive-guide-to-building-apps-with-react/
  3. https://codeburst.io/its-easy-setting-up-react-and-webpack-eb9ecaef5094
  4. https://www.reactenlightenment.com/react-jsx/5.1.html
  5. https://www.slideshare.net/floydophone/react-preso-v2
  6. https://scotch.io/tutorials/javascript-transpilers-what-they-are-why-we-need-them
  7. https://webpack.js.org/guides/getting-started/
  8. https://www.sitepoint.com/yarn-vs-npm/
  9. https://stackoverflow.com/questions/35062852/npm-vs-bower-vs-browserify-vs-gulp-vs-grunt-vs-webpack?rq=1
  10. https://github.com/facebook/flux/tree/master/examples/flux-concepts

Golang: Database migration to manage your database schema by creating incremental SQL

In this post I write down my experience regarding  database migration configuration for Golang using Goose database migration.

Goose installation

$ go get -u github.com/pressly/goose/cmd/goose

This will install the goose binary to your $GOPATH/bin directory.

1.Install
Goose binary installed in bin folder

How to use

$ goose

2.run_goose
Goose executable in action

Create a SQL migration using Goose

$ postgres=# CREATE DATABASE teahrm

3.create-users
Golang SQL migration using Goose
8.empty-migration-generated.png
Just generated empty Migration

Create target database to migrate with

$ goose create create_tables_users sql

4.create-database.png
List of existing databases

Connect to the PostgresSQL database thru psql

$ postgres=# \connect teahrm

Show tables

$ teahrm=# \dt

7.connect-database
Empty database without table yet

Create migration for table users (PostgreSQL datatype)

Migrate Up

goose postgres "user=postgres dbname=teahrm sslmode=disable" up

13.migrate-up.png

Migrate Down

goose postgres "user=postgres dbname=teahrm sslmode=disable" down

14.migrate-down

Common mistake while migrating up

10-common-mitsake
Missing connection information
12.wrongdbname

Wrong database name: goose: no migrations to run. current version: 1

Check Connection status to avoid connection error

goose postgres "user=postgres dbname=postgres sslmode=disable" status

11.connectionstatus

That’s all guys… have a nice weekend…

 

 

 

 

 

Golang: Web development using Gorilla Mux and Pongo2 templating engine

What is Golang Gorilla ?

Gorilla is a web toolkit for the Go programming language.

What is Gorilla mux?

The name mux stands for “HTTP request multiplexer”. Like the standard http.ServeMux, mux.Router matches incoming requests against a list of registered routes and calls a handler for the route that matches the URL or other conditions.

What is HTTP Multiplexer / Mux?

ListenAndServe starts an HTTP server with a given address and handler. The handler is usually nil, which means to use DefaultServeMux. Handle and HandleFunc add handlers to DefaultServeMux

What is Pongo2 ?

pongo2 is the successor of pongo, a Django-syntax like templating-language.

pongo is a well-tested template engine which implements a Django-template-like syntax.

Install Gorilla Mux and Pongo

go get github.com/gorilla/mux
go get -u github.com/flosch/pongo2

Create app.yml

  runtime: go
  api_version: go1 

  handlers:
  - url: /.*
    script: _go_app
    secure: always
    redirect_http_response_code: 301 

create main.go

 package main

  import (
      "net/http"

      pongo "github.com/flosch/pongo2"
      "github.com/gorilla/mux"
  )

  func init() {
      r := mux.NewRouter()

      r.HandleFunc("/", homeHandler)  

      http.Handle("/", r)
  }

  func homeHandler(w http.ResponseWriter, r *http.Request) {
      template := "dashboard.html"
      tmpl := pongo.Must(pongo.FromFile(template))

      err := tmpl.ExecuteWriter(pongo.Context{"title": "Index", "greating": "Hallo"}, w)
      if err != nil {
          http.Error(w, err.Error(), http.StatusInternalServerError)
      }
  }

create base.html

 <html>
      <head>
          <title>
              {% block title %}Website Title Default{% endblock %}
          </title>
      </head>
      <body>
          {% block body %}Body Default{% endblock %}
      </body>
  </html>

create dashboard.html

  {% extends "base.html" %}

  {% block title  %}Dashboard Real Title{% endblock %}

  {% block body %}Hallo world Gorilla!{% endblock %}

Running the code on the local server


dev_appserver.py --port=9999 ./

wakakakak1

bowser1

 

Note: I am using App Engine local environment development