部署
npm run build
创建一个 build
目录,其中包含你的应用的生产版本。设置你最喜欢的 HTTP 服务器,以便为你网站的访问者提供 index.html
,并为对 /static/js/main.<hash>.js
等静态路径的请求提供 /static/js/main.<hash>.js
文件的内容。有关详细信息,请参阅 生产构建 部分。
¥npm run build
creates a build
directory with a production build of your app. Set up your favorite HTTP server so that a visitor to your site is served index.html
, and requests to static paths like /static/js/main.<hash>.js
are served with the contents of the /static/js/main.<hash>.js
file. For more information see the production build section.
静态服务器
¥Static Server
对于使用 Node 的环境,处理此问题的最简单方法是安装 serve 并让它处理其余部分:
¥For environments using Node, the easiest way to handle this would be to install serve and let it handle the rest:
npm install -g serve
serve -s build
上面显示的最后一个命令将在端口 3000 上为你的静态站点提供服务。与 serve 的许多内部设置一样,可以使用 -l
或 --listen
标志调整端口:
¥The last command shown above will serve your static site on the port 3000. Like many of serve’s internal settings, the port can be adjusted using the -l
or --listen
flags:
serve -s build -l 4000
运行此命令以获取可用选项的完整列表:
¥Run this command to get a full list of the options available:
serve -h
其他解决方案
¥Other Solutions
你不一定需要静态服务器才能在生产环境中运行 Create React App 项目。当集成到现有的服务器端应用中时,它也能很好地工作。
¥You don’t necessarily need a static server in order to run a Create React App project in production. It also works well when integrated into an existing server side app.
¥Here’s a programmatic example using Node and Express:
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'build')));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.listen(9000);
服务器软件的选择也不重要。由于 Create React App 完全与平台无关,因此无需显式使用 Node.js。
¥The choice of your server software isn’t important either. Since Create React App is completely platform-agnostic, there’s no need to explicitly use Node.
带有静态资源的 build
文件夹是 Create React App 产生的唯一输出。
¥The build
folder with static assets is the only output produced by Create React App.
但是,如果你使用客户端路由,这还不够。如果你想在单页应用中支持像 /todos/42
这样的 URL,请阅读下一节。
¥However this is not quite enough if you use client-side routing. Read the next section if you want to support URLs like /todos/42
in your single-page app.
使用客户端路由服务应用
¥Serving Apps with Client-Side Routing
如果你使用在引擎盖下使用 HTML5 pushState
历史 API 的路由(例如,React Router 和 browserHistory
),许多静态文件服务器将失败。例如,如果你将 React Router 与 /todos/42
的路由一起使用,开发服务器将正确响应 localhost:3000/todos/42
,但服务于上述生产构建的 Express 则不会。
¥If you use routers that use the HTML5 pushState
history API under the hood (for example, React Router with browserHistory
), many static file servers will fail. For example, if you used React Router with a route for /todos/42
, the development server will respond to localhost:3000/todos/42
properly, but an Express serving a production build as above will not.
这是因为当 /todos/42
有新的页面加载时,服务器查找文件 build/todos/42
但没有找到。服务器需要配置为通过服务 index.html
来响应对 /todos/42
的请求。例如,我们可以修改上面的 Express 示例,为任何未知路径提供 index.html
:
¥This is because when there is a fresh page load for a /todos/42
, the server looks for the file build/todos/42
and does not find it. The server needs to be configured to respond to a request to /todos/42
by serving index.html
. For example, we can amend our Express example above to serve index.html
for any unknown paths:
app.use(express.static(path.join(__dirname, 'build')));
-app.get('/', function (req, res) {
+app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
如果你使用的是 HTTP 服务器,则需要在 public
文件夹中创建一个 .htaccess
文件,如下所示:
¥If you’re using Apache HTTP Server, you need to create a .htaccess
file in the public
folder that looks like this:
Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]
当你运行 npm run build
时,它将被复制到 build
文件夹。
¥It will get copied to the build
folder when you run npm run build
.
如果你使用 Apache Tomcat,则需要遵循 此 Stack Overflow 答案。
¥If you’re using Apache Tomcat, you need to follow this Stack Overflow answer.
现在,对 /todos/42
的请求将在开发和生产中得到正确处理。
¥Now requests to /todos/42
will be handled correctly both in development and in production.
在生产版本中,当你拥有 opted-in 时,服务工作线程 将通过提供 index.html
的缓存副本来自动处理所有导航请求,例如 /todos/42
。这个 service worker 导航路由可以通过 eject
ing 配置或者禁用,然后修改 SWPrecachePlugin
配置的 navigateFallback
和 navigateFallbackWhitelist
选项。
¥On a production build, and when you've opted-in,
a service worker will automatically handle all navigation requests, like for
/todos/42
, by serving the cached copy of your index.html
. This
service worker navigation routing can be configured or disabled by
eject
ing and then modifying the
navigateFallback
and navigateFallbackWhitelist
options of the SWPrecachePlugin
configuration.
当用户将你的应用安装到他们设备的主屏幕时,默认配置会创建一个指向 /index.html
的快捷方式。这可能不适用于希望从 /
提供应用的客户端路由。编辑 public/manifest.json
处的 Web 应用清单并更改 start_url
以匹配所需的 URL 方案,例如:
¥When users install your app to the homescreen of their device the default configuration will make a shortcut to /index.html
. This may not work for client-side routers which expect the app to be served from /
. Edit the web app manifest at public/manifest.json
and change start_url
to match the required URL scheme, for example:
"start_url": ".",
构建相对路径
¥Building for Relative Paths
默认情况下,Create React App 会生成一个构建,假设你的应用托管在服务器根目录下。
¥By default, Create React App produces a build assuming your app is hosted at the server root.
要覆盖它,请在 package.json
中指定 homepage
,例如:
¥To override this, specify the homepage
in your package.json
, for example:
"homepage": "http://mywebsite.com/relativepath",
这将使 Create React App 正确推断要在生成的 HTML 文件中使用的根路径。
¥This will let Create React App correctly infer the root path to use in the generated HTML file.
注意:如果你使用的是 react-router@^4
,则可以在任何 <Router>
上使用 basename
属性来 root <Link>
。
¥Note: If you are using react-router@^4
, you can root <Link>
s using the basename
prop on any <Router>
.
更多信息 此处。
¥More information here.
例如:
¥For example:
<BrowserRouter basename="/calendar"/>
<Link to="/today"/> // renders <a href="/calendar/today">
从不同的路径提供相同的构建
¥Serving the Same Build from Different Paths
注意:
react-scripts@0.9.0
及更高版本提供此功能。¥Note: this feature is available with
react-scripts@0.9.0
and higher.
如果你不使用 HTML5 pushState
history API 或根本不使用客户端路由,则无需指定将从中提供你的应用的 URL。相反,你可以将其放入你的 package.json
:
¥If you are not using the HTML5 pushState
history API or not using client-side routing at all, it is unnecessary to specify the URL from which your app will be served. Instead, you can put this in your package.json
:
"homepage": ".",
这将确保所有资源路径都与 index.html
相关。然后,你将能够将你的应用从 http://mywebsite.com
移动到 http://mywebsite.com/relativepath
甚至 http://mywebsite.com/relative/path
,而无需重新构建它。
¥This will make sure that all the asset paths are relative to index.html
. You will then be able to move your app from http://mywebsite.com
to http://mywebsite.com/relativepath
or even http://mywebsite.com/relative/path
without having to rebuild it.
为任意构建环境自定义环境变量
¥Customizing Environment Variables for Arbitrary Build Environments
你可以通过创建自定义 .env
文件并使用 env-cmd 加载它来创建任意构建环境。
¥You can create an arbitrary build environment by creating a custom .env
file and loading it using env-cmd.
例如,要为暂存环境创建构建环境:
¥For example, to create a build environment for a staging environment:
创建一个名为
.env.staging
的文件¥Create a file called
.env.staging
像设置任何其他
.env
文件(例如REACT_APP_API_URL=http://api-staging.example.com
)一样设置环境变量¥Set environment variables as you would any other
.env
file (e.g.REACT_APP_API_URL=http://api-staging.example.com
)安装 env-cmd
¥Install env-cmd
$ npm install env-cmd --save
$ # or
$ yarn add env-cmd将新脚本添加到你的
package.json
,使用你的新环境进行构建:¥Add a new script to your
package.json
, building with your new environment:{
"scripts": {
"build:staging": "env-cmd -f .env.staging npm run build"
}
}
现在你可以运行 npm run build:staging
以使用暂存环境配置进行构建。你可以以相同的方式指定其他环境。
¥Now you can run npm run build:staging
to build with the staging environment config.
You can specify other environments in the same way.
.env.production
中的变量将用作回退,因为 NODE_ENV
将始终设置为 production
以进行构建。
¥Variables in .env.production
will be used as fallback because NODE_ENV
will always be set to production
for a build.
AWS Amplify
AWS Amplify 控制台为具有无服务器后端的现代 Web 应用(单页应用和静态站点生成器)提供持续部署和托管。Amplify 控制台提供全球可用的 CDN、自定义域设置、功能分支部署和密码保护。
¥The AWS Amplify Console provides continuous deployment and hosting for modern web apps (single page apps and static site generators) with serverless backends. The Amplify Console offers globally available CDNs, custom domain setup, feature branch deployments, and password protection.
登录到 Amplify 控制台 此处。
¥Login to the Amplify Console here.
连接你的 Create React App 存储库并选择一个分支。如果你正在寻找 Create React App+Amplify 启动器,请尝试演示使用 Create React App 在 10 分钟内设置身份验证的 create-react-app-auth-amplify 启动器。
¥Connect your Create React App repo and pick a branch. If you're looking for a Create React App+Amplify starter, try the create-react-app-auth-amplify starter that demonstrates setting up auth in 10 minutes with Create React App.
Amplify 控制台会自动检测构建设置。选择下一步。
¥The Amplify Console automatically detects the build settings. Choose Next.
选择保存并部署。
¥Choose Save and deploy.
如果构建成功,应用将部署并托管在具有 amplifyapp.com 域的全球 CDN 上。你现在可以持续将更改部署到你的前端或后端。持续部署允许开发者在每次代码提交到他们的 Git 存储库时将更新部署到他们的前端和后端。
¥If the build succeeds, the app is deployed and hosted on a global CDN with an amplifyapp.com domain. You can now continuously deploy changes to your frontend or backend. Continuous deployment allows developers to deploy updates to their frontend and backend on every code commit to their Git repository.
Azure
Azure 静态 Web 应用为由 GitHub Actions 提供支持的 React 应用创建一个自动构建和部署管道。默认情况下,应用是地理分布的,具有多个存在点。PR 是为暂存环境预览自动构建的。
¥Azure Static Web Apps creates an automated build and deploy pipeline for your React app powered by GitHub Actions. Applications are geo-distributed by default with multiple points of presence. PR's are built automatically for staging environment previews.
创建一个新的静态 Web 应用 此处。
¥Create a new Static Web App here.
添加详细信息并连接到你的 GitHub 存储库。
¥Add in the details and connect to your GitHub repo.
确保在 "build" 选项卡上正确设置构建文件夹并创建资源。
¥Make sure the build folder is set correctly on the "build" tab and create the resource.
Azure 静态 Web 应用将自动在你的存储库中配置 GitHub Actions 并开始部署。
¥Azure Static Web Apps will automatically configure a GitHub Action in your repo and begin the deployment.
有关路由、API、身份验证和授权、自定义域等的更多信息,请参阅 Azure 静态 Web 应用文档。
¥See the Azure Static Web Apps documentation for more information on routing, APIs, authentication and authorization, custom domains and more.
Firebase
如果你还没有通过运行 npm install -g firebase-tools
安装 Firebase CLI。注册 Firebase 账户 并创建一个新项目。运行 firebase login
并使用你之前创建的 Firebase 账户登录。
¥Install the Firebase CLI if you haven’t already by running npm install -g firebase-tools
. Sign up for a Firebase account and create a new project. Run firebase login
and login with your previous created Firebase account.
然后从项目的根目录运行 firebase init
命令。你需要选择托管:配置和部署 Firebase 托管站点,然后选择你在上一步中创建的 Firebase 项目。你需要同意创建 database.rules.json
,选择 build
作为公共目录,并通过回复 y
同意配置为单页应用。
¥Then run the firebase init
command from your project’s root. You need to choose the Hosting: Configure and deploy Firebase Hosting sites and choose the Firebase project you created in the previous step. You will need to agree with database.rules.json
being created, choose build
as the public directory, and also agree to Configure as a single-page app by replying with y
.
=== Project Setup
First, let's associate this project directory with a Firebase project.
You can create multiple project aliases by running firebase use --add,
but for now we'll set up a default project.
? What Firebase project do you want to associate as default? Example app (example-app-fd690)
=== Database Setup
Firebase Realtime Database Rules allow you to define how your data should be
structured and when your data can be read from and written to.
? What file should be used for Database Rules? database.rules.json
✔ Database Rules for example-app-fd690 have been downloaded to database.rules.json.
Future modifications to database.rules.json will update Database Rules when you run
firebase deploy.
=== Hosting Setup
Your public directory is the folder (relative to your project directory) that
will contain Hosting assets to uploaded with firebase deploy. If you
have a build process for your assets, use your build's output directory.
? What do you want to use as your public directory? build
? Configure as a single-page app (rewrite all urls to /index.html)? Yes
✔ Wrote build/index.html
i Writing configuration info to firebase.json...
i Writing project information to .firebaserc...
✔ Firebase initialization complete!
重要:你需要为 firebase.json
文件中的 service-worker.js
文件设置正确的 HTTP 缓存标头,否则你将无法在首次部署 (问题 #2440) 后看到更改。它应该像下面一样添加到 "hosting"
键中:
¥IMPORTANT: you need to set proper HTTP caching headers for service-worker.js
file in firebase.json
file or you will not be able to see changes after first deployment (issue #2440). It should be added inside "hosting"
key like next:
{
"hosting": {
...
"headers": [
{"source": "/service-worker.js", "headers": [{"key": "Cache-Control", "value": "no-cache"}]}
]
...
现在,在使用 npm run build
创建生产版本后,你可以通过运行 firebase deploy
来部署它。
¥Now, after you create a production build with npm run build
, you can deploy it by running firebase deploy
.
=== Deploying to 'example-app-fd690'...
i deploying database, hosting
✔ database: rules ready to deploy.
i hosting: preparing build directory for upload...
Uploading: [============================== ] 75%✔ hosting: build folder uploaded successfully
✔ hosting: 8 files uploaded successfully
i starting release process (may take several minutes)...
✔ Deploy complete!
Project Console: https://console.firebase.google.com/project/example-app-fd690/overview
Hosting URL: https://example-app-fd690.firebaseapp.com
有关详细信息,请参阅 Firebase 托管。
¥For more information see Firebase Hosting.
GitHub Pages
注意:
react-scripts@0.2.0
及更高版本提供此功能。¥Note: this feature is available with
react-scripts@0.2.0
and higher.
步骤 1:将 homepage
添加到 package.json
¥Step 1: Add homepage
to package.json
下面的步骤很重要!
¥The step below is important!
如果你跳过它,你的应用将无法正确部署。
¥If you skip it, your app will not deploy correctly.
打开你的 package.json
并为你的项目添加一个 homepage
字段:
¥Open your package.json
and add a homepage
field for your project:
"homepage": "https://myusername.github.io/my-app",
或者对于 GitHub 用户页面:
¥or for a GitHub user page:
"homepage": "https://myusername.github.io",
或自定义域页面:
¥or for a custom domain page:
"homepage": "https://mywebsite.com",
Create React App 使用 homepage
字段来确定构建的 HTML 文件中的根 URL。
¥Create React App uses the homepage
field to determine the root URL in the built HTML file.
步骤 2:安装 gh-pages
并将 deploy
添加到 package.json
中的 scripts
¥Step 2: Install gh-pages
and add deploy
to scripts
in package.json
现在,无论何时运行 npm run build
,你都会看到一张备忘单,其中包含有关如何部署到 GitHub Pages 的说明。
¥Now, whenever you run npm run build
, you will see a cheat sheet with instructions on how to deploy to GitHub Pages.
要在 https://myusername.github.io/my-app 上发布它,请运行:
¥To publish it at https://myusername.github.io/my-app, run:
npm install --save gh-pages
或者你可以使用 yarn
:
¥Alternatively you may use yarn
:
yarn add gh-pages
在你的 package.json
中添加以下脚本:
¥Add the following scripts in your package.json
:
"scripts": {
+ "predeploy": "npm run build",
+ "deploy": "gh-pages -d build",
"start": "react-scripts start",
"build": "react-scripts build",
predeploy
脚本将在 deploy
运行之前自动运行。
¥The predeploy
script will run automatically before deploy
is run.
如果你要部署到 GitHub 用户页面而不是项目页面,你需要进行一项额外的修改:
¥If you are deploying to a GitHub user page instead of a project page you'll need to make one additional modification:
调整
package.json
脚本以将部署推送到主目录:¥Tweak your
package.json
scripts to push deployments to main:
"scripts": {
"predeploy": "npm run build",
- "deploy": "gh-pages -d build",
+ "deploy": "gh-pages -b main -d build",
步骤 3:通过运行 npm run deploy
部署站点
¥Step 3: Deploy the site by running npm run deploy
然后运行:
¥Then run:
npm run deploy
步骤 4:对于项目页面,请确保项目的设置使用 gh-pages
¥Step 4: For a project page, ensure your project’s settings use gh-pages
最后,确保 GitHub 项目设置中的 GitHub Pages 选项设置为使用 gh-pages
分支:
¥Finally, make sure GitHub Pages option in your GitHub project settings is set to use the gh-pages
branch:
步骤 5:(可选)配置域
¥Step 5: Optionally, configure the domain
你可以通过将 CNAME
文件添加到 public/
文件夹来使用 GitHub Pages 配置自定义域。
¥You can configure a custom domain with GitHub Pages by adding a CNAME
file to the public/
folder.
你的 CNAME 文件应如下所示:
¥Your CNAME file should look like this:
mywebsite.com
客户端路由注意事项
¥Notes on client-side routing
GitHub Pages 不支持在后台使用 HTML5 pushState
历史记录 API 的路由(例如,使用 browserHistory
的 React Router)。这是因为当像 http://user.github.io/todomvc/todos/42
这样的 url 有新的页面加载时,其中 /todos/42
是前端路由,GitHub Pages 服务器返回 404,因为它对 /todos/42
一无所知。如果你想将路由添加到 GitHub Pages 上托管的项目,这里有几个解决方案:
¥GitHub Pages doesn’t support routers that use the HTML5 pushState
history API under the hood (for example, React Router using browserHistory
). This is because when there is a fresh page load for a url like http://user.github.io/todomvc/todos/42
, where /todos/42
is a frontend route, the GitHub Pages server returns 404 because it knows nothing of /todos/42
. If you want to add a router to a project hosted on GitHub Pages, here are a couple of solutions:
你可以从使用 HTML5 历史 API 切换到使用哈希路由。如果你使用 React Router,你可以切换到
hashHistory
来实现这个效果,但是 URL 会更长更冗长(例如,http://user.github.io/todomvc/#/todos/42?_k=yknaj
)。阅读更多 关于 React Router 中不同的历史实现。¥You could switch from using HTML5 history API to routing with hashes. If you use React Router, you can switch to
hashHistory
for this effect, but the URL will be longer and more verbose (for example,http://user.github.io/todomvc/#/todos/42?_k=yknaj
). Read more about different history implementations in React Router.或者,你可以使用一个技巧来教 GitHub Pages 处理 404,方法是使用自定义重定向参数重定向到你的
index.html
页面。在部署项目之前,你需要将带有重定向代码的404.html
文件添加到build
文件夹,并且你需要将处理重定向参数的代码添加到index.html
。你可以找到此技术的详细说明 在本指南中。¥Alternatively, you can use a trick to teach GitHub Pages to handle 404s by redirecting to your
index.html
page with a custom redirect parameter. You would need to add a404.html
file with the redirection code to thebuild
folder before deploying your project, and you’ll need to add code handling the redirect parameter toindex.html
. You can find a detailed explanation of this technique in this guide.
故障排除
¥Troubleshooting
“/dev/tty:没有这样的设备或地址”
¥"/dev/tty: No such a device or address"
如果在部署时出现 /dev/tty: No such a device or address
或类似错误,请尝试以下操作:
¥If, when deploying, you get /dev/tty: No such a device or address
or a similar error, try the following:
创建一个新的 个人访问令牌
¥Create a new Personal Access Token
git remote set-url origin https://<user>:<token>@github.com/<user>/<repo>
。再试试
npm run deploy
¥Try
npm run deploy
again
"无法读取 null 的属性 'email'"
¥"Cannot read property 'email' of null"
如果在部署时获得 Cannot read property 'email' of null
,请尝试以下操作:
¥If, when deploying, you get Cannot read property 'email' of null
, try the following:
git config --global user.name '<your_name>'
git config --global user.email '<your_email>'
再试试
npm run deploy
¥Try
npm run deploy
again
Heroku
使用 用于创建 React 应用的 Heroku Buildpack。
¥Use the Heroku Buildpack for Create React App.
你可以在 零配置部署 React 中找到说明。
¥You can find instructions in Deploying React with Zero Configuration.
解决 Heroku 部署错误
¥Resolving Heroku Deployment Errors
有时 npm run build
在本地工作,但在通过 Heroku 部署期间失败。以下是最常见的情况。
¥Sometimes npm run build
works locally but fails during deploy via Heroku. Following are the most common cases.
“未找到模块:错误:无法解析 'file' 或 'directory'”
¥"Module not found: Error: Cannot resolve 'file' or 'directory'"
如果你得到这样的东西:
¥If you get something like this:
remote: Failed to create a production build. Reason:
remote: Module not found: Error: Cannot resolve 'file' or 'directory'
MyDirectory in /tmp/build_1234/src
这意味着你需要确保你 import
的文件或目录的字母大小写与你在文件系统或 GitHub 上看到的相匹配。
¥It means you need to ensure that the lettercase of the file or directory you import
matches the one you see on your filesystem or on GitHub.
这很重要,因为 Linux(Heroku 使用的操作系统)区分大小写。所以 MyDirectory
和 mydirectory
是两个不同的目录,因此,即使项目在本地构建,大小写上的差异也会破坏 Heroku 遥控器上的 import
语句。
¥This is important because Linux (the operating system used by Heroku) is case sensitive. So MyDirectory
and mydirectory
are two distinct directories and thus, even though the project builds locally, the difference in case breaks the import
statements on Heroku remotes.
"找不到所需的文件。"
¥"Could not find a required file."
如果你从包中排除或忽略必要的文件,你将看到类似以下的错误:
¥If you exclude or ignore necessary files from the package you will see a error similar this one:
remote: Could not find a required file.
remote: Name: `index.html`
remote: Searched in: /tmp/build_a2875fc163b209225122d68916f1d4df/public
remote:
remote: npm ERR! Linux 3.13.0-105-generic
remote: npm ERR! argv "/tmp/build_a2875fc163b209225122d68916f1d4df/.heroku/node/bin/node" "/tmp/build_a2875fc163b209225122d68916f1d4df/.heroku/node/bin/npm" "run" "build"
在这种情况下,请确保该文件以正确的字母大小写存在,并且不会在你的本地 .gitignore
或 ~/.gitignore_global
上被忽略。
¥In this case, ensure that the file is there with the proper lettercase and that’s not ignored on your local .gitignore
or ~/.gitignore_global
.
Netlify
手动部署到 Netlify 的 CDN:
¥To do a manual deploy to Netlify’s CDN:
npm install netlify-cli -g
netlify deploy
选择 build
作为部署路径。
¥Choose build
as the path to deploy.
要设置持续交付:
¥To setup continuous delivery:
使用此设置,当你推送到 git 或打开拉取请求时,Netlify 将构建和部署:
¥With this setup Netlify will build and deploy when you push to git or open a pull request:
选择你的 Git 托管服务并选择你的存储库
¥Pick your Git hosting service and select your repository
点击
Build your site
¥Click
Build your site
支持客户端路由:
¥Support for client-side routing:
要支持 pushState
,请确保创建具有以下重写规则的 public/_redirects
文件:
¥To support pushState
, make sure to create a public/_redirects
file with the following rewrite rules:
/* /index.html 200
当你构建项目时,Create React App 会将 public
文件夹内容放入构建输出中。
¥When you build the project, Create React App will place the public
folder contents into the build output.
Vercel
Vercel 是一个云平台,使开发者能够托管 Jamstack 网站和 Web 服务,这些网站和 Web 服务可即时部署、自动扩展且无需监督,所有这些均采用零配置。它们提供全球边缘网络、SSL 加密、资源压缩、缓存失效等。
¥Vercel is a cloud platform that enables developers to host Jamstack websites and web services that deploy instantly, scale automatically, and requires no supervision, all with zero configuration. They provide a global edge network, SSL encryption, asset compression, cache invalidation, and more.
步骤 1:将 React 项目部署到 Vercel
¥Step 1: Deploying your React project to Vercel
要使用 用于 Git 集成的 Vercel 部署 React 项目,请确保它已被推送到 Git 存储库。
¥To deploy your React project with a Vercel for Git Integration, make sure it has been pushed to a Git repository.
使用 导入流程 将项目导入 Vercel。在导入过程中,你会发现所有相关的 options 都已为你预先配置,并且可以根据需要进行更改。
¥Import the project into Vercel using the Import Flow. During the import, you will find all relevant options preconfigured for you with the ability to change as needed.
导入项目后,所有后续的分支推送都会生成 预览部署,对 生产分支(通常为 "master" 或 "main")所做的所有更改都会生成 生产部署。
¥After your project has been imported, all subsequent pushes to branches will generate Preview Deployments, and all changes made to the Production Branch (commonly "master" or "main") will result in a Production Deployment.
部署后,你将获得一个 URL 以实时查看你的应用,例如:https://create-react-app-example.vercel.app/。
¥Once deployed, you will get a URL to see your app live, such as the following: https://create-react-app-example.vercel.app/.
步骤 2(可选):使用自定义域
¥Step 2 (optional): Using a Custom Domain
如果你想在 Vercel 部署中使用自定义域,你可以通过 Vercel 账户域设置。 在你的域中添加或转移
¥If you want to use a Custom Domain with your Vercel deployment, you can Add or Transfer in your domain via your Vercel account Domain settings.
要将你的域添加到你的项目,请从 Vercel 仪表板导航到你的 项目。选择项目后,单击 "设置" 选项卡,然后选择“域”菜单项。在你的项目域页面中,输入你想要添加到项目中的域。
¥To add your domain to your project, navigate to your Project from the Vercel Dashboard. Once you have selected your project, click on the "Settings" tab, then select the Domains menu item. From your projects Domain page, enter the domain you wish to add to your project.
添加域后,你将看到不同的配置方法。
¥Once the domain has been added, you will be presented with different methods for configuring it.
部署一个新的 React 项目
¥Deploying a fresh React project
你可以部署一个新的 React 项目,为你设置一个 Git 存储库,使用以下部署按钮:
¥You can deploy a fresh React project, with a Git repository set up for you, with the following Deploy Button:
Vercel 参考资料:
¥Vercel References:
Render
Render 提供免费的 静态站点 托管,具有完全托管的 SSL、全球 CDN 和来自 GitHub 的持续自动部署。
¥Render offers free static site hosting with fully managed SSL, a global CDN and continuous auto deploys from GitHub.
按照 创建 React App 部署指南 在几分钟内部署你的应用。
¥Deploy your app in only a few minutes by following the Create React App deployment guide.
使用邀请码 cra
注册或使用 这个链接。
¥Use invite code cra
to sign up or use this link.
S3 和 CloudFront
¥S3 and CloudFront
请参阅此 博文,了解如何将 React 应用部署到 Amazon Web Services S3 和 CloudFront。如果你希望添加自定义域、HTTPS 和持续部署,请参阅此 博文。
¥See this blog post on how to deploy your React app to Amazon Web Services S3 and CloudFront. If you are looking to add a custom domain, HTTPS and continuous deployment see this blog post.
Surge
如果你还没有通过运行 npm install -g surge
安装 Surge CLI。运行 surge
命令并登录你或创建一个新账户。
¥Install the Surge CLI if you haven’t already by running npm install -g surge
. Run the surge
command and log in you or create a new account.
当询问项目路径时,确保指定 build
文件夹,例如:
¥When asked about the project path, make sure to specify the build
folder, for example:
project path: /path/to/project/build
请注意,为了支持使用 HTML5 pushState
API 的路由,你可能需要在部署到 Surge 之前将构建文件夹中的 index.html
重命名为 200.html
。这个 确保每个 URL 回退到该文件。
¥Note that in order to support routers that use HTML5 pushState
API, you may want to rename the index.html
in your build folder to 200.html
before deploying to Surge. This ensures that every URL falls back to that file.
发布组件到 npm
¥Publishing Components To npm
Create React App 不提供任何将组件发布到 npm 的内置功能。如果你准备好从你的项目中提取一个组件以便其他人可以使用它,我们建议你将它移动到你项目之外的一个单独的目录,然后使用像 nwb 这样的工具来准备发布。
¥Create React App doesn't provide any built-in functionality to publish a component to npm. If you're ready to extract a component from your project so other people can use it, we recommend moving it to a separate directory outside of your project and then using a tool like nwb to prepare it for publishing.