ReactJS - CLI 命令
React 有自己的命令行界面 (CLI) 命令。但是,这些 CLI 命令目前仅用于使用命令行创建 React 应用程序的可传递版本。这将包含一个默认模板作为其设计,因此以这种方式创建的所有 React 应用程序都将具有很好的一致性,因为它们都具有相同的结构。
React 中的基本 CLI 命令
让我们在本章中学习 Create React App 命令行应用程序中可用的基本命令。
创建新应用程序
Create React App 提供多种创建 React 应用程序的方法。
使用 npx 脚本。
npx create-react-app <react-app-name> npx create-react-app hello-react-app
使用 npm 包管理器。
npm init react-app <react-app-name> npm init react-app hello-react-app
使用 yarn 包管理器。
yarn init react-app <react-app-name> yarn init react-app hello-react-app
选择模板
Create React App 使用默认模板创建 React 应用程序。模板是指具有某些内置功能的初始代码。npm 包服务器中有数百个具有许多高级功能的模板。 Create React App 允许用户通过 -template 命令行开关选择模板。
create-react-app my-app --template typescript
上述命令将使用来自 npm 服务器的 cra-template-typescript 包创建 React 应用。
安装依赖项
可以使用常规 npm 或 yarn 包命令安装 React 依赖项包,因为 React 使用 npm 和 yarn 推荐的项目结构。
使用 npm 包管理器。
npm install --save react-router-dom
使用 yarn 包管理器。
yarn add react-router-dom
运行应用程序
可以使用 npm 或 yarn 命令启动 React 应用程序,具体取决于项目中使用的包管理器。
使用 npm 包管理器。
npm start
使用 yarn 包管理器。
yarn start
要在安全模式 (HTTPS) 下运行应用程序,请在启动应用程序之前设置环境变量 HTTPS 并将其设置为 true。例如,在 Windows 命令提示符 (cmd.exe) 中,以下命令设置 HTTPS 并以 HTTPS 模式启动应用程序。
set HTTPS=true && npm start