typescript - עבודה עם yarn-workspace, לציין את תיקיית השורש של החבילה כדי לקבל נתיב ייבוא נוח יותר
הקשר
אני עובד עם yarn-workspace ו-typescript.
שקול את מבנה הפרויקט הבא:
project/
|- package.json
|- packages/
| |- common/
| | |- build/
| | | `- src/
| | | |- myFile.d.ts
| | | `- myFile.js
| | |- package.json
| | `- src/
| | | `- myFile.ts
| | `- tsconfig.json
| `- app/
| |- package.json
| |- src/
| | `- index.ts
| `- tsconfig.json
`- yarn.lock
// packages/common/src/myFile.ts
export function functionFromCommon(): void {
console.log("Greetings from common");
}
בעיה
הבעיה שלי היא שכאשר אני מנסה להתייחס ל-functionFromCommon מהתיקייה "app", אני צריך לכתוב את הדברים הבאים :
// packages/app/src/index
import { functionFromCommon } from 'common/build/src/myFile';
functionFromCommon();
מה שהייתי רוצה זה למצוא דרך לכתוב רק import {} from "common/myFile" כאשר מתייחסים לזה מחבילות אחרות.
אני יודע שאני יכול לאגד את כל החבילות הנפוצות שלי בנקודת כניסה אחת index.js אבל אני רוצה לשמור על מבנה התיקיה כפי שהוא כדי לכתוב:
import { f1 } from "common/moduleA";
import { f2 } from "common/moduleB";
ניסיתי לבדוק מה ניתן לציין ב-package.json (סוג של שדה "mainFolder") אבל לא הצלחתי למצוא כלום.
מידע נוסף
לידיעתך, קבצי package.json נראים כך :
// root package.json
{
"name": "project",
"license": "MIT",
"workspaces": [
"packages/*"
]
}
// packages/common/package.json
{
"name": "common",
"version": "1.0.0",
"license": "MIT",
"dependencies": {},
"devDependencies": {
"@types/node": "^14.0.4",
"typescript": "^3.9.3"
}
}
// packages/app/package.json
{
"name": "app",
"version": "1.0.0",
"license": "MIT",
"dependencies": {
"common": "1.0.0"
},
"devDependencies": {
"@types/node": "^14.0.4",
"typescript": "^3.9.3"
}
}
וקובץ tsconfig.json שניהם ככה:
{
"include": ["src"],
"compilerOptions": {
/* Basic Options */
"incremental": true,
"declaration": true,
"target": "ES2020",
"module": "commonjs",
"sourceMap": true,
"outDir": "./build",
"types": ["node"],
"composite": true,
"tsBuildInfoFile": "./build/tsbuildinfo.json",
/* Strict Type-Checking Options */
"strict": true,
/* Module Resolution Options */
"moduleResolution": "node",
"esModuleInterop": true
}
}
עדכון: (13-10-2020)
שדה חדש בשם "exports" נוסף ל-package.json כדי להגדיר בדיוק את זה. ניתן למצוא מידע נוסף כאן: https://nodejs.org/docs/latest-v12.x/api/esm.html#esm_exports_sugar.
אבל זה כרגע לא נתמך על ידי TypeScript...
הצלחתי לקבל גרסה פועלת על ידי ביצוע פתרון עקיפה זה: https://github.com/microsoft/TypeScript/issues/33079#issuecomment-702617758.