มือใหม่ Nuxt.js + TypeScript pt.2 การใช้ TypeScript ใน Nuxt.js เบื้องต้น

แนวทางการพัฒนาเว็บแอปพลิเคชั่นด้วย Nuxt.js + Typescript สำหรับมือใหม่

สวัสดีครับ มาต่อกันที่พาร์ทที่ 2 ซึ้งพาร์ทนี้เราจะเริ่มเอา Typescript ที่เข้าใจ Concept กันแล้วเมื่อพาร์ทที่ 1 มาใช้ร่วมงานกับ Nuxt.js กัน

⚠️ ใครที่ยังไม่เข้าใจ Concept ของ Typescript ก็สามารถกดย้อนไปอ่านพาร์ทที่หนึ่งก่อนได้ตามลิ้งนี้เลยนะครับ https://mnagon.gitbook.io/blog/nuxt.js-+-typescript-pt.1-nuxt.js

⚠️ บทความนี้ไม่มีส่วนของพื้นฐาน Node.js นะครับ เพราะฉนั้นแล้วหากใครยังไม่คุ้นเคยกับ Node.js อาจจะต้องศึกษาพื้นฐานเพิ่มเติมนิดหน่อยครับ แนะนำตามลิ้งนี้ครับ https://www.w3schools.com/nodejs/default.asp

⚠️ บทความนี้จะไม่มีส่วนของพื้นฐาน Vue.js เพราะฉนั้นแล้วหากใครที่ยังไม่คุ้นชินกับ Vue.js อาจต้องศึกษาพื้นฐานของ Vue.js ก่อนถึงจะต่อยอดมา Nuxt.js ได้นะครับ สามารถศึกษาเพิ่มเติมได้จากลิ้งนี้เลยครับ https://vuejs.org/v2/guide/

ติดตั้ง Nuxt.js + Typescript

อันดับแรกเราก็เปิด command ขึ้นมา แล้วบรรเลงคำสั่งติดตั้งนี้ลงไปได้เลยครับ

npm init nuxt-app <project-name>

ส่วนสำคัญของเรามีแค่หลังจากพิมพ์คำสั่งเสร็จเรียบร้อยแล้วถึงช่วงต้องเลือก Programming language ให้เราเลือกเป็น TypeScript ตามรูปเลยครับ

เลือก TypesScript สำหรับตัวเลือก Programming language

นอกเหนือจากนี้แล้วเลือกหรือไม่เลือกอะไรก็แล้วแต่ครับ ส่วนที่เกี่ยวข้องกับบทความนี้มีแค่นี้แหละ 😆

ติดตั้งแบบ manual?

สำหรับใครที่มีโปรเจ็ค Nuxt.js อยู่แล้วและต้องการ Install แบบ manual ให้ใช้คำสั่งนี้แทนครับ

npm install --save-dev @nuxt/typescript-build @nuxt/types

หลังจากติดตั้งแพคเกจเรียบร้อยแล้ว ให้เราเปิดไฟล์ nuxt.config.js ขึ้นมา แล้วเพิ่ม '@nuxt/typescript-build' เข้าไปในส่วนของ buildModules ครับ

export default {

  ...
  
  buildModules: [
    '@nuxt/typescript-build',
  ],
  
  ...
  
}

หลังจากนั้นให้สร้างไฟล์ tsconfig.json ให้เหมือนด้านล่างนี้ครับ

{
  "compilerOptions": {
    "target": "ES2018",
    "module": "ESNext",
    "moduleResolution": "Node",
    "lib": [
      "ESNext",
      "ESNext.AsyncIterable",
      "DOM"
    ],
    "esModuleInterop": true,
    "allowJs": true,
    "sourceMap": true,
    "strict": true,
    "noEmit": true,
    "experimentalDecorators": true,
    "baseUrl": ".",
    "paths": {
      "~/*": [
        "./*"
      ],
      "@/*": [
        "./*"
      ]
    },
    "types": [
      "@nuxt/types",
      "@types/node"
    ]
  },
  "exclude": [
    "node_modules",
    ".nuxt",
    "dist"
  ]
}

เพียงเท่านี้ก็เสร็จสิ้นการติดตั้ง TypeScript บน Nuxt.js โปรเจ็คแล้วครับ

ใช้ TypeScript กับ Vue component

ประกาศใช้ TypeScript ใน script

ในไฟล์ .vue ของเรา ในส่วนของ script ให้เราเพิ่ม lang="ts" เข้าไปตรง tag script แบบนี้ครับ

<script lang="ts">

</script>

export vue.extend() แทนการ export object module

ในแท็ก script เราต้อง import Vue from 'vue' แล้วเปลี่ยนจากการ export default {} ธรรมดาให้กลายเป็น export default Vue.extend({}) แบบนี้ครับ

<script lang="ts">
import Vue from 'vue'

export default Vue.extend({})
</script>

กำหนด name ให้ component

หากเราต้องการเรียกใช้ component นี้ใน component อื่นด้วยเราจำเป็นต้องเพิ่ม name properties ให้กับ Vue.extend({}) ของเราแบบนี้ครับ

export default Vue.extend({
  name: 'MyComponent',
})

กำหนด Type ให้กับ data

Vue component เดิม ในส่วนของ data นั้นจะเป็น function ที่ return object ออกไป ดังนั้นเราต้องใช้วิธีการกำหนด type ให้กับ object ซึ้งนั้นก็คือการสร้าง interface ขึ้นมา หลังจากนั้นเราจะให้ data ของเรา return object type ที่เราได้สร้าง interface ไว้ออกมานั้นเอง อธิบายแล้วงง ๆ ดูตัวอย่างกันดีกว่า

interface Contact {
  address: string
  phone: string
}

interface State {
  name: string
  age: number
  favorite: string[]
  contact: Contact
}

export default Vue.extend({

  ...

  data(): State {
    return {
      name: 'mnagon',
      age: 27,
      favorite: ['code', 'game'],
      contact: {
        address: 'Chaing mai',
        phone: '',
      },
    }
  },
})

จะเห็นว่าผมได้สร้าง interface ชื่อ State แล้วหลังจากนั้นผมได้เปลี่ยน data ของผมให้เป็น function type State และ return object type State ออกไปนั่นเอง

methods, computed, watch function ต้องมี type ด้วยนะ

เหมือนการกำหนด Type ให้กับ function ทั่วไปเลยครับ หาเป็น function ที่ return ค่าออกมาเราก็ต้องกำหนด type ตามค่าที่ output ออกมา หากไม่มี output ก็กำหนดให้เป็น void นั้นเองครับ ตัวอย่างแบบนี้ครับ

export default Vue.extend({

  ...

  computed: {
    getBirthYear(): number {
      return new Date().getFullYear() - this.age
    },
    favoriteString: {
      get(): string {
        return this.favorite.join(',')
      },
      set(val: string): void {
        this.favorite = val.split(',')
      },
    },
  },

  watch: {
    favorite(): void {
      console.log('favorite change')
    },
  },

  methods: {
    addFavorite(favorite: string): void {
      this.favorite.push(favorite)
    },
  },
})

การกำหนด Props

สำหรับการ props นั้นหากเราต้องรับ props เข้ามาเป็น object แน่นอนว่าเราต้องสร้าง interface ไว้รองรับ props ที่จะเข้ามา แต่ทว่าเราไม่สามารถนำ Type ที่เราสร้างไว้มาใส่ใน type ของ props ได้แบบตรง ๆ เราต้อง import ตัวช่วยเข้ามาอีกตัวชื่อว่า propsType และกำหนดค่าให้ props ของเราออกมาแบบนี้ครับ

import Vue, { PropType } from 'vue'

interface Contact {
  address: string
  phone: string
}

interface User {
  name: string
  age: number
  favorite: string[]
  contact: Contact
}

export default Vue.extend({
  props: {
    user: {
      type: Object as PropType<User>,
      required: true,
    },
    message: {
      type: String,
      default: 'message...',
    },
  },

})

แหละนี้คือตัวอย่างของโค้ดทั้งหมดอีกครั้งครับ อาจจะไม่ใช้โค้ดที่เอาไปใช้งานได้จริงจังอะไร แต่ก็พยายามโชว์ให้เห็น Concept ของการใช้ TypeScript ร่วมกับ Nuxt.js ให้ได้มากที่สุดครับ

<script lang="ts">
import Vue, { PropType } from 'vue'

interface Contact {
  address: string
  phone: string
}

interface User {
  name: string
  age: number
  favorite: string[]
  contact: Contact
}

interface State {
  title: string
}

export default Vue.extend({
  name: 'MyComponent',

  props: {
    user: {
      type: Object as PropType<User>,
      required: true,
    },
    message: {
      type: String,
      default: 'some message',
    },
  },

  data(): State {
    return {
      title: 'Nuxt.js + TypeScript',
    }
  },

  computed: {
    getBirthYear(): number {
      return new Date().getFullYear() - this.age
    },
    favoriteString: {
      get(): string {
        return this.favorite.join(',')
      },
      set(val: string): void {
        this.favorite = val.split(',')
      },
    },
  },

  watch: {
    favorite(): void {
      console.log('favorite change')
    },
  },

  methods: {
    addFavorite(favorite: string): void {
      this.favorite.push(favorite)
    },
  },
})
</script>

จบแล้วครับเบื้องต้นของการใช้ TypeScript ร่วมกับ Nuxt.js หวังว่าจะเป็นประโยชน์กับใครที่กำลังสนใจใช้ TypeScript ร่วมกับ Nuxt.js แต่ยังไม่ค่อยเข้าใจ Concept นะครับ สุดท้ายแล้วขอบคุณที่สนใจอ่านจนจบครับ 🙏

💡 สำหรับใครที่อยากศึกษาให้ลึกเข้าไปอีกสามารถตามลิ้งนี้ไปได้เลยครับ https://typescript.nuxtjs.org/

🙋‍♂️ นี้ถือเป็นบทความแรกที่ผมเขียนในชีวิตเลย ผมไม่ใช่ผู้เชี่ยวชาญที่นำความรู้มาสอน เป็นแค่นักเขียนโค้ดที่ยังคงเรียนรู้อยู่ และมาแชร์สิ่งที่ได้เผื่อว่าเป็นประโยชน์กับใครได้บ้าง หากมีข้อผิดพลาดจุดไหนประการใด ผมขออภัยไว้ตรงนี้นะครับ 🙏

Last updated

Was this helpful?