TypeScript
Day.js 內建 TypeScript 的官方類型宣告,並在 NPM 套件中提供。
透過 NPM 安裝
npm install dayjs
在 TypeScript 檔案中匯入並使用
import * as dayjs from 'dayjs'
dayjs().format()
匯入 Day.js 有問題嗎?
如果你的 tsconfig.json
包含以下設定,你必須執行預設匯入工作流程 import dayjs from 'dayjs'
{ //tsconfig.json
"compilerOptions": {
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
}
}
如果你沒有上述設定,預設匯入將無法運作,你必須繼續使用 import * as dayjs from 'dayjs'
地區和外掛匯入
要使用地區和外掛,你首先需要匯入目標語言和外掛。
import * as dayjs from 'dayjs'
import * as isLeapYear from 'dayjs/plugin/isLeapYear' // import plugin
import 'dayjs/locale/zh-cn' // import locale
dayjs.extend(isLeapYear) // use plugin
dayjs.locale('zh-cn') // use locale