如何构建含types和functions子目录的TypeScript本地NPM包
构建支持指定导入方式的TypeScript NPM包方案
一、目录结构调整
基于你现有的目录,只需给types和utils目录添加入口文件,最终结构如下:
wordle-shared ├── src │ ├── types │ │ ├── index.ts # 统一导出所有类型 │ │ └── move.ts # 存放Move类型定义 │ └── utils │ ├── index.ts # 统一导出所有工具函数 │ └── validWords.ts # 存放getValidWords函数实现 ├── package.json ├── tsconfig.json ├── .gitignore
二、核心文件编写
- src/types/move.ts
export interface Move { word: string; result: string[]; // 可添加其他类型字段 }
- src/types/index.ts
export { Move } from './move'; // 后续新增类型都在此统一导出
- src/utils/validWords.ts
export function getValidWords(): string[] { // 这里写函数逻辑 return ['apple', 'grape', 'lemon']; }
- src/utils/index.ts
export { getValidWords } from './validWords'; // 后续新增工具函数都在此统一导出
三、package.json关键配置
如果用@前缀(比如@wordle/shared)属于作用域包,适合团队内部共享,直接修改包名即可。核心配置如下:
{ "name": "wordle-shared", // 或 "@wordle/shared"(作用域包) "version": "1.0.0", "type": "module", "main": "./dist/index.js", "types": "./dist/index.d.ts", "exports": { ".": "./dist/index.js", "./types": "./dist/types/index.js", "./utils": "./dist/utils/index.js" }, "typesVersions": { "*": { "types": ["./dist/types/index.d.ts"], "utils": ["./dist/utils/index.d.ts"] } }, "scripts": { "build": "tsc" }, "devDependencies": { "typescript": "^5.0.0" } }
exports:明确子路径的导出映射,让Node.js和打包工具识别wordle-shared/types这类导入路径typesVersions:为TypeScript提供子路径的类型文件映射,保证类型提示正常工作
四、tsconfig.json配置
确保编译产物输出到dist目录并保留结构:
{ "compilerOptions": { "target": "ES2020", "module": "ESNext", "declaration": true, "outDir": "./dist", "strict": true, "moduleResolution": "node", "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "include": ["src/**/*"], "exclude": ["node_modules", "dist"] }
declaration: true:自动生成类型声明文件(.d.ts)outDir: "./dist":编译产物统一输出到dist目录
五、本地测试与使用
- 在
wordle-shared目录执行npm run build编译代码 - 执行
npm link将包链接到本地全局 - 在你的Wordle项目中执行
npm link wordle-shared(作用域包则执行npm link @wordle/shared) - 此时即可按照需求导入:
import { Move } from "wordle-shared/types"; import { getValidWords } from "wordle-shared/utils";
内容的提问来源于stack exchange,提问作者nikord
相关产品推荐
相关产品推荐

