在React-Styleguidist的Markdown文件中使用TypeScript遇语法错误求助
React-Styleguidist Markdown中使用TypeScript抛出SyntaxError的解决办法
我在React项目里集成了React-Styleguidist(版本^13.1.1)生成组件文档,TypeScript已经装了最新版且配置正确,但在Markdown文件里写TypeScript代码描述组件属性类型时,生成文档总会抛出SyntaxError,提示TS代码有语法问题。搜了一圈没找到明确解决办法,求帮忙。
相关代码与配置
1. styleguide.config.js
module.exports = { components: 'src/components/**/*.tsx', propsParser: require('react-docgen-typescript').withCustomConfig('./tsconfig.json').parse, // 其他自定义配置 };
2. Button.tsx
import React from 'react'; interface ButtonProps { /** 按钮显示文本 */ text: string; /** 是否禁用按钮 */ disabled?: boolean; /** 点击事件回调 */ onClick?: () => void; } const Button: React.FC<ButtonProps> = ({ text, disabled = false, onClick }) => { return ( <button disabled={disabled} onClick={onClick}> {text} </button> ); }; export default Button;
3. Button.md
# Button 按钮 基础操作触发组件。 ## 属性类型 ```ts interface ButtonProps { text: string; disabled?: boolean; onClick?: () => void; }
使用示例
<Button text="确认" onClick={() => alert('按钮被点击')} /> <Button text="禁用状态" disabled />
### 4. 错误提示
SyntaxError: Unexpected token (2:10)
1 | interface ButtonProps {
2 | text: string;
| ^
3 | disabled?: boolean;
4 | onClick?: () => void;
--- ## 可行解决步骤 ### 1. 确认TypeScript解析配置正确 React-Styleguidist默认用`react-docgen`处理JS组件,TS组件必须依赖`react-docgen-typescript`解析。先确保这个包已安装: ```bash npm install react-docgen-typescript --save-dev # 或 yarn add react-docgen-typescript -D
然后在styleguide.config.js里补全TypeScript支持配置:
module.exports = { components: 'src/components/**/*.tsx', // 启用TypeScript支持 typescript: true, // 绑定正确的tsconfig路径 propsParser: require('react-docgen-typescript').withCustomConfig('./tsconfig.json').parse, };
2. 给Markdown里的TS代码块指定正确语言标识
React-Styleguidist不会自动识别未标注语言的代码块为TS,必须明确写ts或typescript作为代码块标识:
// 正确写法:开头指定ts interface ButtonProps { text: string; disabled?: boolean; }
别犯这些错误:
- 不写语言标识:直接用```包裹代码
- 错误指定为
js:```js包裹TS代码
3. 检查tsconfig.json配置
确保你的tsconfig.json没有语法解析冲突:
{ "compilerOptions": { "target": "ES6", "module": "ESNext", "jsx": "react-jsx", // 适配React 17+的JSX转换 "strict": true, "esModuleInterop": true, "skipLibCheck": true }, "include": ["src/**/*"] // 包含所有组件和相关文件 }
4. 兼容Webpack配置(如果自定义过)
如果在styleguide.config.js里改了Webpack配置,必须添加TS loader支持:
module.exports = { // ...其他配置 webpackConfig: { module: { rules: [ { test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/, }, ], }, resolve: { extensions: ['.tsx', '.ts', '.js'], }, }, };
记得安装ts-loader:
npm install ts-loader --save-dev
5. 更新依赖版本
尝试更新相关依赖到兼容版本,避免版本冲突:
npm update react-styleguidist react-docgen-typescript typescript
内容的提问来源于stack exchange,提问作者jeremie legrand
相关产品推荐
相关产品推荐

