vscode如何开发react
配置开发环境
确保已安装最新版VS Code和Node.js(包含npm或yarn)。通过终端验证安装:
node -v
npm -v
创建React项目
使用Create React App快速初始化项目:
npx create-react-app my-app
cd my-app
code .
安装必备扩展
在VS Code扩展商店安装以下工具:
- ES7+ React/Redux/React-Native snippets:提供代码片段快捷生成
- Prettier - Code formatter:代码格式化
- ESLint:代码质量检查
- Debugger for Chrome:调试支持
配置项目设置
在项目根目录创建.vscode/settings.json并添加:
{
"editor.formatOnSave": true,
"javascript.preferences.quoteStyle": "single",
"typescript.updateImportsOnFileMove.enabled": "always"
}
启动开发服务器
在集成终端运行:
npm start
这将自动打开浏览器访问http://localhost:3000
调试配置
创建.vscode/launch.json并添加配置:
{
"version": "0.2.0",
"configurations": [
{
"type": "chrome",
"request": "launch",
"name": "Launch Chrome",
"url": "http://localhost:3000",
"webRoot": "${workspaceFolder}"
}
]
}
组件开发示例
创建src/components/Button.js:
import React from 'react';
import PropTypes from 'prop-types';
const Button = ({ children, onClick }) => (
<button
className="primary-button"
onClick={onClick}
>
{children}
</button>
);
Button.propTypes = {
children: PropTypes.node.isRequired,
onClick: PropTypes.func
};
export default Button;
样式管理
推荐使用CSS Modules。创建src/styles/Button.module.css:
.primary-button {
padding: 12px 24px;
background: #646cff;
color: white;
border: none;
border-radius: 4px;
}
在组件中引入:
import styles from './Button.module.css';
// 使用方式: className={styles['primary-button']}
常用快捷键
Ctrl+Shift+P:打开命令面板Ctrl+`:打开集成终端rfc+Tab:快速生成函数组件模板Ctrl+Shift+F:全局搜索F12:跳转到定义







