Benben
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # [JS102] 升級你的 JavaScript 技能:ES6 + npm + Jest ###### Date : 2021 Apr. 26 - 2021 Apr. 27 #### 模組化 & Library - require 把功能切分開來,方便之後維護 > index.js ```javascript // node 原生 os 套件 var os = require('os') console.log(os.platform()) ``` - export >myModule.js ```javascript function double(n) { return n * 2 } // 將寫好的 function 打包成 obj var obj = { double: double, triple: function(n) { return n * 3 }, } // 將 obj 輸出出去 // module.exports 也可以輸出 number, string, array ...等 module.exports = obj // 另一種輸出方法,但此種方法僅限輸出 object exports.double = double exports.triple = triple ``` >index.js ```javascript // 引入 myModule , './' 表示當前目錄 var myModule = require('./myModule') console.log(myModule.double(2), myModule.triple(10)) // 6, 30 ``` #### NPM : Node Package Manager - npm 安裝 & 使用套件 > command line ```shell $ npm install left-pad ## 安裝套件 $ npm init ## 初始化 NPM ,並產生 package.json $ npm install left-pad --save ## 安裝套件並儲存套件資訊到 package.json 的 "dependencies" $ npm install left-pad --save-dev ## 安裝套件並儲存套件資訊到 package.json 的 "devDependencies" $ npm install ## 安裝 package.json 裡的所有套件 ## commit 的時候,記得把 node_module 資料夾排除 ## 本地端要用的時候,再用 npm install 安裝 ## 補充資訊: ## 從 npm 5 以後,--save 就已經變成預設的選項了,因此 npm install 不加 --save 也是可以的喔,一樣會把資訊寫到 package.json 裡面去! ``` > index.js ```javascript var leftPad = require('left-pad') console.log(leftPad(123, 10, '0')) // 0000000123 ``` - NPM Script > package.json ```json "script" : { "start": "node index.js", "test": "echo \"Error: no test specified\" && exit 1", "hello": "echo hello world" }, ``` > command line ```shell $ npm run start $ npm run hello ## hello world ``` - yarn | [yarn 官網](https://classic.yarnpkg.com/en/) 跟 npm 87% 像,由 facebook 開發,語法稍簡單、速度較快,也很多人使用,用 npm & yarn 都可以。 #### 寫測試,單元測試 Unit Test - 最陽春的方法,console.log ```javascript console.log( 'output' === 'result' ) ``` - Jest | [Jest 官網](https://jestjs.io/) > command line ```shell $ yarn add --dev jest ## 安裝 jest $ jest ## 測試所有專案資料夾下的 *.test.js 檔 $ jest index.test.js ## 錯誤 : command not found: jest ## 因為 jest 沒有安裝在 global 環境下 *在 package.json 裡的 scripts 裡增加 "test": "jest index.test.js", $ npm run test ## 將 jest 寫在 package.json 裡就可以執行了,或是使用以下 npx 方法 $ npx jest index.test.js ## 新版的 npm 支援,在專案資料夾下找到 jest 這個東西 ``` > index.js ```javascript function myFunction(input){ // code } module.exports = myFunction // 一定要 export 出去才可以測試 ``` > index.test.js ```javascript var myFunction = require('./index') // 使用 describe 群組化 test 資料,非必要但比較好看 describe('測試 myFunction', function() { test('測試 1 應該要等於 輸出1', function() { expect(myFunction(INPUT1).toBe('OUTPUT1')) }) test('測試 2 應該要等於 輸出2', function() { expect(myFunction(INPUT2).toBe('OUTPUT2')) }) test('測試 3 應該要等於 輸出3', function() { expect(myFunction(INPUT3).toBe('OUTPUT3')) }) }) ``` - TDD : Test-drive Development ( 測試驅動開發 ) 先寫測試 &rArr 再寫程式 測試資料盡可能完整一點,邊測試邊開發 #### ECMAScript2015 (ES6) | [ECMA 規格書](https://www.ecma-international.org/publications-and-standards/standards/ecma-262/) - var v.s. let & const const 宣告的變數不可以重新賦職 var 的 Scope 是以 function 為單位 let 的 Scope 是以 block `{}` 為單位 - Template Literals ( 字串模板 ) ```javascript let name = 'ben' // 不用再用 + 拼接 console.log(`hi ${name}`) // hi ben ``` - Destructuring ( 解構 ) ```javascript // destructur array const arr = [1, 2, 3, 4] let [first, second] = arr console.log(first, second) // 1, 2 // destructur object const obj = { name: 'nick', age: 30, address: 'taiwan', } let {address} = obj console.log(address) // taiwan // destructur double object const obj = { name: 'nick', age: 30, address: 'taiwan', family: { father: 'adam', } } let {family:{father}} = obj console.log(father) // adam // destructur function function ({a, b}){ console.log(a) } test({ a: 1, b: 2 }) // 1 ``` - Spread Operator ( 展開運算子 ) ```javascript // spread array let arr1 = [2, 3, 4] let arr2 = [1, ...arr1, 5] console.log(arr2) // [1, 2, 3, 4, 5] // spread array in function function add(a, b, c){ return a + b + c } let arr = [1, 2, 3] console.log(add(...arr)) // 6 ``` > `...` 無法巢狀展開 - Rest Parameters ( 剩餘參數 ) ```javascript let arr = [1, 2, 3, 4] let [first, ...rest] = arr conosle.log(rest) // [2, 3, 4] let obj = { a: 1, b: 2, c: 3, } let {a, ...obj2} = obj console.log(a, obj2) // 1, {b: 2, c: 3} ``` > `...rest` 只能放最後面 - Default Parameters ( 預設值 ) ```javascript function repeat(str, times = 2) { return str.repeat(times) } console.log('abc') // abcabc ``` - Arrow function ( 箭頭函式 ) ```javascript const double = n => return n*2 ``` - Import & Export > util.js ```javascript export function add(a, b) { return a + b } export const Pi = 3.1415926535 // 也可以這樣寫 export { add as addFunction, PI } // 或是這樣寫 export default function add(a, b) { return a + b } // imorpt 就不用大括號 import add from './utils' ``` > index.js ```javascript import {add, PI} form './utils' console.log(add(3 + 5), PI) // 8, 3.1415 // 也可以這樣寫 import {addFunction as a , PI} form './utils' console.log(a(3 + 5), PI) // 8, 3.1415 // 或是這樣寫 import * as utils from './utils' console.log(utils.addFunction(3, 5), PI) // 8, 3.1415 ``` > terninal ```shell ## 如果 node.js 不支援 ES6 語法,使用 babel $ npx babel-node index.js ``` - Babel | [Babel 官網](https://babeljs.io/) 將 ES6/7/8 => ES5 等等 :::info Babel 的安裝說明:https://babeljs.io/docs/en/next/babel-node.html 設定步驟: 安裝必要套件:npm install --save-dev @babel/core @babel/node @babel/preset-env 新增 .babelrc 填入內容,告訴 babel 要用這個 preset: { "presets": ["@babel/preset-env"] } 最後使用 npx babel-node index.js 即可 ::: #### Ref. - [如何看待 Azer Koçulu 刪除了自己的所有 npm 庫?](https://www.zhihu.com/question/41694868) - [抽掉 11 行程式就讓網路大崩塌!一場撞名事件,看開源的威力與權力衝突。](https://www.inside.com.tw/article/6041-how-one-programmer-broke-the-internet-by-deleting-a-tiny-piece-of-code) - [es6-cheatsheet](https://github.com/DrkSephy/es6-cheatsheet) --- ##### 心得 模組化真的很方便,雖然還沒真的遇到覺得方便的時候,因為我現在寫的 code 大多也不超過 30 行,如果你跟我一樣有看超過 10 行 code 就會死的病,就會體會到模組化的威力了😂😂😂 NPM 固然方便,但是在 left-pad 這個例子上, Azer Koçulu 刪除了自己的所有 npm 庫,可以發現 dependencies 的問題,網路開源的方便性,也顯示了人的惰性,Huli 的學生絕對可以自己寫出來 left-pad 這個套件,但同時我也相信寫不出來的大有人在🤔,不然不會造成這麼大的波及。 在我上這門課之前,都有聽說要寫測試、寫測試,但甚麼是測試?還有測試的重要性?原來這就是測試,以前只會陽春的 console.log 現在多了 Jest 這個測試 framework 還有 TDD 這個開發方法感覺又升級了。 最後 ES6 也是扎實的教好教滿,當然沒有全教,因為太多了太深了,講不完,但現在這樣就夠用了,先熟練這些好用的新武器吧。

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully