Shared Package - Dayjs
在 Lint 這篇有介紹到如何設定共用的 config, 這邊以 dayjs 為例紀錄一下如何在 pnpm 中讓其他 project 使用共享的 package
1. 在 packages/ 底下建立 package, 並安裝 dayjs
note
packages/
可參考自己的 pnpm-workspace.yaml 設定來更換所需位置
pnpm-workspace.yaml
packages:
- 'apps/**'
- 'packages/**'
- 'website/**'
# exclude packages that are inside test directories
- '!**/test/**'
pnpm add dayjs typescript --filter YOUR_PACKAGE_NAME
2. 建立要 export 給其他 project 使用的 utility
在 src/index.ts
建立 utility, 然後建立自己需要的功能
src/index.ts
import dayjs, { ManipulateType, Dayjs, ConfigType } from 'dayjs';
import weekday from 'dayjs/plugin/weekday';
import localeData from 'dayjs/plugin/localeData';
import timezone from 'dayjs/plugin/timezone';
import localizedFormat from 'dayjs/plugin/localizedFormat';
import 'dayjs/locale/zh-tw';
import 'dayjs/locale/en';
dayjs.extend(weekday);
dayjs.extend(localeData);
dayjs.extend(timezone);
dayjs.extend(localizedFormat);
export class DateUtility {
private timeZone: string;
constructor(timeZone: string = 'Asia/Taipei') {
this.timeZone = timeZone;
}
public isToday(date: ConfigType, lang: string = this.timeZone): boolean {
if (!dayjs(date).isValid()) return false;
const now = dayjs(new Date()).locale(lang);
return dayjs(date).locale(lang).isSame(now, 'day');
}
public now(lang: string = this.timeZone): Dayjs {
return dayjs().locale(lang);
}
}
const dateUtil = new DateUtility();
export default dateUtil;
note
TypeScript 的設定可以參考官方文件
這時候目前的結構會類似這樣
YOUR_PACKAGE_NAME
├── node_modules
│ └── dayjs
├── src
│ └── index.ts
├── package.json
└── tsconfig.json
3. 調整 package.json 輸出的設定
在 package.json
中更新設定
package.json
{
"name": "@repo/dayjs",
"version": "1.0.0",
"description": "dayjs-lib",
"main": "dist/index.js",
"scripts": {
"build": "tsc"
},
"dependencies": {
"dayjs": "^1.11.11",
"typescript": "^5.4.5"
},
"exports": {
".": "./dist/index.js"
}
}
exports
這個設定是告訴其他 project 要 import 的檔案位置
當完成後就可以執行 pnpm build
來產生 dist
資料夾
4. 在其他 project 中使用
在其他專案中安裝 package:
package.json
{
"name": "api",
"version": "0.0.1",
"description": "API server using NestJS",
"private": true,
"scripts": {
"dev": "dotenv -e .env -- nest start --watch"
},
"dependencies": {
"@repo/dayjs": "workspace:^"
},
"devDependencies": {}
}
然後在想要用的地方使用:
user.service.ts
// ...
import dateUtil from '@repo/dayjs';
@Injectable()
export class UserService {
// ...
async updateUserById({ _id, user = {} }: { _id: string; user?: Partial<UserDocument> }) {
// ...
const updateQuery = {
$set: {
...user,
updatedAt: dateUtil.now().toISOString()
}
};
// ...
}
}