Lerna Monorepo本地开发JSDoc失效,发布至NPM后正常求助
嘿,我之前在Lerna monorepo里也碰到过一模一样的JSDoc丢失问题,结合你的场景,给你几个实用的解决方案:
1. 在API包的入口index文件中补全导出注释
因为Webpack Dev Server本地解析模块时,没法自动追踪到深层文件的JSDoc,所以在index中转导出时,需要在导出语句上重新添加完整的JSDoc注释。比如:
// API包的src/index.js /** * Get comments from JSON placeholder API * @namespace API * @module * @param {GetCommentsRequestExample} input PostId * @returns {Promise.<GetCommentsResponseExample>} Array of comments */ export { getComments } from './services/comments'; // 替换成你的实际文件路径
这样本地开发时,Web包就能直接读取到index文件里的JSDoc,和你直接在index里写函数的效果一致。
2. 添加TypeScript类型声明文件(兼容纯JS项目)
如果你的项目能接受引入TypeScript类型声明(不需要完全转成TS),这是最稳定的方案。在API包根目录创建index.d.ts文件,手动定义函数和类型的注释:
// API包/index.d.ts /** * @typedef {Object} GetCommentsRequestExample * @property {number} postId - 要获取评论的帖子ID */ /** * @typedef {Object} GetCommentsResponseExample * @property {number} id - 评论ID * @property {string} body - 评论内容 */ /** * Get comments from JSON placeholder API * @namespace API * @param {GetCommentsRequestExample} input PostId * @returns {Promise<GetCommentsResponseExample[]>} 评论数组 */ export declare function getComments(input: GetCommentsRequestExample): Promise<GetCommentsResponseExample[]>;
然后在API包的package.json里指定类型文件路径:
{ "types": "./index.d.ts" }
不管是本地开发还是发布到NPM,Web包都能正确识别这些类型和注释。
3. 调整Webpack Dev Server的模块解析配置
有时候Webpack的软链接解析策略会影响JSDoc的读取,你可以在Web包的Webpack配置里,强制直接读取API包的源码,而不是依赖Lerna创建的软链接:
// Web包的webpack.config.js const path = require('path'); module.exports = { // ...其他配置 resolve: { symlinks: false, // 禁用软链接解析 modules: [ 'node_modules', path.resolve(__dirname, '../api/src') // 直接添加API包源码路径 ] } };
注意要根据你的项目目录结构调整路径,这个方法能让Webpack直接解析API包的源码文件,从而读取到里面的JSDoc。
4. 用JSDoc的@exports明确导出类型
在getComments所在的文件里,确保所有用到的自定义类型都用@typedef定义并通过@exports导出,然后在index文件中一并导出这些类型:
// API包/src/services/comments.js /** * @typedef {Object} GetCommentsRequestExample * @property {number} postId - 要获取评论的帖子ID * @exports GetCommentsRequestExample */ /** * @typedef {Object} GetCommentsResponseExample * @property {number} id - 评论ID * @property {string} body - 评论内容 * @exports GetCommentsResponseExample */ /** * Get comments from JSON placeholder API * @namespace API * @module * @param {GetCommentsRequestExample} input PostId * @returns {Promise.<GetCommentsResponseExample[]>} 评论数组 */ export const getComments = input => apiGet('https://jsonplaceholder.typicode.com/comments', input, GetCommentsRequest, GetCommentsResponse);
然后在index文件中导出类型和函数:
// API包/src/index.js export { getComments, GetCommentsRequestExample, GetCommentsResponseExample } from './services/comments';
这样Webpack在解析模块时,能更准确地追踪到类型定义和对应的JSDoc注释。
我自己当初用第一种方法快速解决了问题,因为不需要引入额外工具,只需要补几行注释就行,适合纯JS项目。如果你的API包规模持续增长,第二种TypeScript类型声明的方法会更持久可靠。
内容的提问来源于stack exchange,提问作者Fralle

