如何启动react文件
启动 React 项目的方法
使用 Create React App
安装 Create React App(CRA)工具,快速生成 React 项目模板。
npx create-react-app my-app
进入项目目录并启动开发服务器。
cd my-app
npm start
默认情况下,开发服务器会在 http://localhost:3000 启动。
使用 Vite
Vite 是一个更轻量、更快速的 React 项目启动工具。安装 Vite 并创建 React 项目。
npm create vite@latest my-react-app --template react
进入项目目录并安装依赖。
cd my-react-app
npm install
启动开发服务器。
npm run dev
手动配置 Webpack
如果需要更灵活的配置,可以手动设置 Webpack 和 Babel。 初始化项目并安装必要的依赖。
npm init -y
npm install react react-dom
npm install --save-dev webpack webpack-cli babel-loader @babel/core @babel/preset-env @babel/preset-react
创建 webpack.config.js 文件并配置加载规则。
module.exports = {
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
},
},
],
},
};
创建 .babelrc 文件并配置预设。
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
在 package.json 中添加启动脚本。
"scripts": {
"start": "webpack serve --mode development"
}
运行启动命令。
npm start
使用 Yarn
如果更喜欢使用 Yarn 作为包管理工具,可以用以下命令创建和启动项目。
yarn create react-app my-app
cd my-app
yarn start
使用 TypeScript 模板
如果需要 TypeScript 支持,可以在创建项目时指定模板。
npx create-react-app my-app --template typescript
启动方式与普通 React 项目相同。
cd my-app
npm start






