該項目用Create React應用程序進行了引導。
在下面,您將找到有關如何執行常見任務的一些信息。
您可以在此處找到本指南的最新版本。
<title>
public
文件夾public
文件夾.env
中添加開發環境變量<meta>
標籤npm start
未檢測到更改npm test
在Macos Sierra上懸掛或撞車npm run build
出口太早npm run build
在Heroku上失敗npm run build
無法縮小Create React應用程序分為兩個軟件包:
create-react-app
是您用於創建新項目的全局命令行實用程序。react-scripts
是生成項目的開發依賴性(包括該項目)。您幾乎不需要更新create-react-app
本身:它將所有設置委託給react-scripts
。
當您運行create-react-app
時,它總是使用最新版本的react-scripts
創建項目,因此您將自動獲得新創建的應用程序中的所有新功能和改進。
要將現有項目更新為新版本的react-scripts
,請打開ChangElog,查找您當前的版本(如果不確定,請在此文件package.json
中進行檢查),並應用較新的遷移說明版本。
在大多數情況下,在package.json
和在此文件夾中運行npm install
(或yarn install
)中的react-scripts
版本應該足夠了,但是最好諮詢ChangElog以獲取潛在的破壞更改。
我們致力於保持最小的破壞變化,以便您可以輕鬆地升級react-scripts
。
我們總是對您的反饋開放。
創建後,您的項目應該看起來像這樣:
my-app/
README.md
node_modules/
package.json
public/
index.html
favicon.ico
src/
App.css
App.js
App.test.js
index.css
index.js
logo.svg
為了構建項目,這些文件必須具有確切的文件名存在:
public/index.html
是頁面模板;src/index.js
是JavaScript入口點。您可以刪除或重命名其他文件。
您可以在src
內部創建子目錄。對於更快的重建,WebPack僅處理src
中的文件。
您需要將所有JS和CSS文件放在src
中,否則WebPack不會看到它們。
只能從public/index.html
中使用public
內部的文件。
閱讀下面使用JavaScript和HTML資產的說明。
但是,您可以創建更多頂級目錄。
它們將不包括在生產構建中,因此您可以將它們用於文檔之類的東西。
在項目目錄中,您可以運行:
npm start
在開發模式下運行該應用程序。
打開http:// localhost:3000在瀏覽器中查看。
如果您進行編輯,該頁面將重新加載。
您還將在控制台中看到任何棉絨錯誤。
npm test
在交互式手錶模式下啟動測試跑者。
有關更多信息,請參見有關運行測試的部分。
npm run build
將應用程序構建到build
文件夾中。
它正確地捆綁了在生產模式下進行反應,並優化構建以獲得最佳性能。
構建被縮小,文件名包括哈希。
您的應用已準備好部署!
有關更多信息,請參見有關部署的部分。
npm run eject
注意:這是一個單向操作。 eject
後,您將無法返回!
如果您對構建工具和配置選擇不滿意,則可以隨時eject
。此命令將從您的項目中刪除單個構建依賴關係。
取而代之的是,它將將所有配置文件和傳遞依賴性(webpack,babel,eslint等)複製到您的項目中,以便您完全控制它們。除eject
以外的所有命令仍然可以工作,但是它們將指向複製的腳本,以便您可以調整它們。在這一點上,您是一個人。
您不必使用eject
。策劃的功能集適用於中小型部署,您不應該感到有義務使用此功能。但是,我們知道,如果您在準備好後,您無法自定義該工具,則該工具將沒有用。
默認情況下,生成的項目支持所有現代瀏覽器。
對Internet Explorer 9、10和11的支持需要多填充。
該項目支持最新JavaScript標準的超集。
除了ES6語法功能外,它還支持:
了解有關不同建議階段的更多信息。
雖然我們建議使用一些謹慎使用實驗建議,但Facebook在產品代碼中大量使用這些功能,因此我們打算在將來的任何建議中提供CODEMODS。
請注意,默認情況下,該項目不包括多填充。
如果您使用需要運行時支持的任何其他ES6+功能(例如Array.from()
或Symbol
),請確保您手動包含適當的polyfills,或者您針對的瀏覽器已經支持它們。
要配置您喜歡的文本編輯器中的語法突出顯示,請轉到相關的Babel文檔頁面並按照說明進行操作。涵蓋了一些最受歡迎的編輯。
注意:此功能可提供
[email protected]
及更高版本。
它還僅適用於NPM 3或更高。
一些編輯器(包括崇高的文本,原子和Visual Studio代碼)為ESLINT提供插件。
它們不是覆蓋所必需的。您應該在終端以及瀏覽器控制台中看到Linter輸出。但是,如果您希望棉絨結果出現在編輯器中,那麼您可以執行一些額外的步驟。
您需要首先為編輯器安裝ESLINT插件。然後,將一個名為.eslintrc
的文件添加到項目root:
{
"extends" : "react-app"
}
現在,您的編輯應報告伸縮警告。
請注意,即使您進一步編輯.eslintrc
文件,這些更改也只會影響編輯器集成。它們不會影響終端和瀏覽器棉絨輸出。這是因為創建React應用程序有意提供了一組最小的規則,這些規則會發現常見錯誤。
如果您想為項目執行編碼樣式,請考慮使用更漂亮而不是ESLINT樣式規則。
目前,此功能僅由Visual Studio Code和WebStorm支持。
Visual Studio代碼和WebStorm支持使用Create React應用程序開箱即用。這使您可以作為開發人員在不離開編輯器的情況下編寫和調試您的React代碼,最重要的是,它使您能夠具有連續的開發工作流程,因為您不必在工具之間切換,因此上下文切換很小。
您需要安裝最新版本的VS代碼和VS代碼Chrome調試器擴展名。
然後將下面的塊添加到您的launch.json
文件中,然後將其放入應用程序根目錄中的.vscode
文件夾中。
{
"version" : " 0.2.0 " ,
"configurations" : [
{
"name" : " Chrome " ,
"type" : " chrome " ,
"request" : " launch " ,
"url" : " http://localhost:3000 " ,
"webRoot" : " ${workspaceRoot}/src " ,
"sourceMapPathOverrides" : {
"webpack:///src/*" : " ${webRoot}/* "
}
}
]
}
注意:如果您通過主機或端口環境變量進行了調整,則URL可能會有所不同。
通過運行npm start
來啟動應用程序,並通過按F5
或單擊綠色調試圖標開始在VS代碼中進行調試。現在,您可以編寫代碼,設置斷點,更改代碼,並從編輯器中調試您的新修改的代碼。
vs代碼調試有問題嗎?請參閱他們的故障排除指南。
您需要安裝WebStorm和Jetbrains IDE支持Chrome擴展。
在WebStorm菜單中Run
選擇Edit Configurations...
然後單擊+
,然後選擇JavaScript Debug
。粘貼http://localhost:3000
進入URL字段並保存配置。
注意:如果您通過主機或端口環境變量進行了調整,則URL可能會有所不同。
通過運行npm start
開始您的應用程序,然後在Windows和Linux上按MACOS或F9
按^D
,或單擊Green Debug圖標以開始在WebStorm中調試。
您可以在Intellij Ideas Ultimate,PhpStorm,Pycharm Pro和Rubymine中調試應用程序的方式。
Prettier是一種自以為是的代碼格式化器,並支持JavaScript,CSS和JSON。借助更漂亮,您可以將您自動編寫的代碼格式化,以確保項目中的代碼樣式。有關更多信息,請參見Prettier的GitHub頁面,並查看此頁面以查看它的作用。
每當我們在git中提交代碼時,我們都需要安裝以下依賴項:
npm install --save husky lint-staged prettier
或者,您可以使用yarn
:
yarn add husky lint-staged prettier
husky
使使用githooks變得容易,就好像它們是NPM腳本一樣。lint-staged
允許我們在git中的分階段文件上運行腳本。請參閱此博客文章有關絨毛片段的文章,以了解有關它的更多信息。prettier
是我們將在提交之前運行的JavaScript格式化器。現在,我們可以通過在項目root中的package.json
中添加幾行來確保每個文件正確格式化。
將以下字段添加到package.json
部分:
+ "husky": {
+ "hooks": {
+ "pre-commit": "lint-staged"
+ }
+ }
接下來,我們將“絨毛級”字段添加到package.json
。
"dependencies": {
// ...
},
+ "lint-staged": {
+ "src/**/*.{js,jsx,json,css}": [
+ "prettier --single-quote --write",
+ "git add"
+ ]
+ },
"scripts": {
現在,每當您進行提交時,Prettier都會自動格式化更改的文件。您也可以運行./node_modules/.bin/prettier --single-quote --write "src/**/*.{js,jsx}"
以首次格式化整個項目。
接下來,您可能需要將更漂亮的編輯整合到您喜歡的編輯中。在Prettier GitHub頁面上閱讀有關編輯器集成的部分。
<title>
您可以在生成項目的public
文件夾中找到源HTML文件。您可以在其中編輯<title>
標籤,以將標題從“ React App”更改為其他任何內容。
請注意,通常您不會經常在public
文件夾中編輯文件。例如,添加樣式表是在不觸摸HTML的情況下完成的。
如果您需要根據內容動態更新頁面標題,則可以使用瀏覽器document.title
。標題API。對於更複雜的方案,當您想從React組件中更改標題時,可以使用第三方庫React Helmet。
如果您在生產中使用自定義服務器為應用程序使用,並希望在將標題發送到瀏覽器之前對其進行修改,則可以在本節中遵循建議。另外,您可以將每個頁面預先構建為靜態HTML文件,然後加載JavaScript捆綁包,此處介紹。
生成的項目包括React和Reactdom作為依賴關係。它還包括創建React應用程序作為開發依賴性的一組腳本。您可以使用npm
安裝其他依賴項(例如React Router):
npm install --save react-router-dom
或者,您可以使用yarn
:
yarn add react-router-dom
這適用於任何庫,而不僅僅是react-router-dom
。
由於WebPack,該項目設置支持ES6模塊。
雖然您仍然可以使用require()
和module.exports
,但我們鼓勵您使用import
和export
。
例如:
Button.js
import React , { Component } from 'react' ;
class Button extends Component {
render ( ) {
// ...
}
}
export default Button ; // Don’t forget to use export default!
DangerButton.js
import React , { Component } from 'react' ;
import Button from './Button' ; // Import a component from another file
class DangerButton extends Component {
render ( ) {
return < Button color = "red" / > ;
}
}
export default DangerButton ;
請注意默認和命名導出之間的區別。這是錯誤的常見來源。
我們建議您在模塊僅導出單個東西(例如組件)時堅持使用默認的導入和導出。這就是您使用export default Button
和import Button from './Button'
時得到的。
命名導出對於導出多個功能的實用程序模塊很有用。一個模塊最多可能具有一個默認導出,並且隨心所欲。
了解有關ES6模塊的更多信息:
代碼拆分,代替用戶可以使用它,而不是在用戶使用之前下載整個應用程序,而是可以將代碼拆分為小塊,然後可以按需加載代碼。
該項目設置支持通過Dynamic import()
分裂代碼。它的建議在階段3中。 import()
函數式表單將模塊名稱作為參數,並返回一個始終解決模塊名稱空間對象的Promise
。
這是一個示例:
moduleA.js
const moduleA = 'Hello' ;
export { moduleA } ;
App.js
import React , { Component } from 'react' ;
class App extends Component {
handleClick = ( ) => {
import ( './moduleA' )
. then ( ( { moduleA } ) => {
// Use moduleA
} )
. catch ( err => {
// Handle failure
} ) ;
} ;
render ( ) {
return (
< div >
< button onClick = { this . handleClick } > Load < / button >
< / div >
) ;
}
}
export default App ;
這將使moduleA.js
及其所有獨特的依賴項作為單獨的塊,僅在用戶單擊“加載”按鈕之後加載。
如果您願意,也可以將其與async
/ await
語法一起使用。
如果您使用的是React路由器,請查看有關如何使用代碼分配的教程。您可以在此處找到同伴GitHub存儲庫。
還要查看React文檔中的代碼分裂部分。
該項目設置使用WebPack來處理所有資產。 WebPack提供了一種自定義方法,可以“擴展”超出JavaScript的import
概念。為了表明JavaScript文件取決於CSS文件,您需要從JavaScript文件導入CSS :
Button.css
. Button {
padding : 20 px ;
}
Button.js
import React , { Component } from 'react' ;
import './Button.css' ; // Tell Webpack that Button.js uses these styles
class Button extends Component {
render ( ) {
// You can use them as regular CSS styles
return < div className = "Button" / > ;
}
}
React並不需要這一點,但是許多人發現此功能方便。您可以在此處閱讀有關此方法的好處。但是,您應該意識到,這會使您的代碼與WebPack相比,您的代碼較低於其他構建工具和環境。
在開發中,以這種方式表達依賴關係可以使您的樣式在編輯時即可隨時重新加載。在生產中,所有CSS文件都將在構建輸出中加入單個縮小的.css
文件。
如果您擔心使用特定於WebPack的語義,則可以將所有CSS直接放入src/index.css
中。它仍將從src/index.js
導入,但是如果您以後遷移到其他構建工具,則可以隨時刪除該導入。
注意:此功能可提供
[email protected]
及更高版本。
該項目使用[name].module.css
文件命名約定以及常規樣式表支持CSS模塊。 CSS模塊允許通過自動創建格式[filename]_[classname]__[hash]
的唯一className來範圍。
提示:如果您想用SASS預處理樣式表,請確保遵循安裝說明,然後按以下方式更改樣式表文件擴展名:
[name].module.scss
或[name].module.sass
。
CSS模塊可讓您在不同文件中使用相同的CSS類名稱,而不必擔心命名衝突。在此處了解有關CSS模塊的更多信息。
Button.module.css
. error {
background-color : red;
}
another-stylesheet.css
. error {
color : red;
}
Button.js
import React , { Component } from 'react' ;
import styles from './Button.module.css' ; // Import css modules stylesheet as styles
import './another-stylesheet.css' ; // Import regular stylesheet
class Button extends Component {
render ( ) {
// reference as a js object
return < button className = { styles . error } > Error Button < / button > ;
}
}
沒有其他衝突.error
<!-- This button has red background but not red text -->
< button class =" Button_error_ax7yz " > </ div >
這是一個可選功能。常規<link>
樣式表和CSS文件得到了充分支持。 CSS模塊以.module.css
擴展為結尾的文件打開。
注意:此功能可提供
[email protected]
及更高版本。
通常,我們建議您不要在不同組件上重複使用相同的CSS課程。例如,我們建議使用自己的.Button
樣式創建一個.Button
css類,而是在<AcceptButton>
and <RejectButton>
組件中使用<Button>
components, <AcceptButton>
and <ackeptbutton> and <RejectButton>
都可以呈現(但不要繼承)。
遵循此規則通常會使CSS預處理器的用處降低,因為Mixins和Nesting之類的功能由組件組成代替。但是,如果您發現它很有價值,則可以集成CSS預處理器。
要使用SASS,請首先安裝node-sass
:
$ npm install node-sass --save
$ # or
$ yarn add node-sass
現在,您可以將src/App.css
重命名為src/App.scss
,然後更新src/App.js
以導入src/App.scss
。如果用Extension .scss
或.sass
導入此文件和任何其他文件,將自動編譯。
要在SASS文件之間共享變量,您可以使用SASS導入。例如, src/App.scss
和其他組件樣式文件可以包括@import "./shared.scss";
具有可變定義。
這將使您像
@import ' styles/_colors.scss ' ; // assuming a styles directory under src/
@import ' ~nprogress/nprogress ' ; // importing a css file from the nprogress node module
提示:您也可以選擇與CSS模塊一起使用此功能!
注意:您必須從
node_modules
導入~
,如上所述。
該項目設置可將您的CSS縮小,並通過自動改裝器自動添加供應商前綴,因此您無需擔心它。
支持新的CSS功能,例如all
屬性, break
屬性,自定義屬性和媒體查詢範圍自動填充,以增加對較舊瀏覽器的支持。
您可以通過調整package.json
中的browserslist
鍵來自定義目標支持瀏覽器。
例如,這個:
. App {
display : flex;
flex-direction : row;
align-items : center;
}
變成了:
. App {
display : -webkit-box;
display : -ms-flexbox;
display : flex;
-webkit-box-orient : horizontal;
-webkit-box-direction : normal;
-ms-flex-direction : row;
flex-direction : row;
-webkit-box-align : center;
-ms-flex-align : center;
align-items : center;
}
如果由於某種原因需要禁用自動修復,請遵循本節。
默認情況下禁用CSS網格佈局前綴,但不會剝離手動前綴。如果您想選擇進入CSS網格前綴,請首先熟悉其限制。
要啟用CSS網格前綴,請添加/* autoprefixer grid: on */
到CSS文件的頂部。
使用WebPack,使用圖像和字體之類的靜態資產與CSS相似。
您可以在JavaScript模塊中直接import
文件。這告訴WebPack將該文件包含在捆綁包中。與CSS導入不同,導入文件為您提供字符串值。此值是您可以在代碼中引用的最終路徑,例如,作為圖像的src
屬性或鏈接到PDF的href
。
為了減少服務器的請求數量,導入少於10,000個字節的圖像返回數據URI而不是路徑。這適用於以下文件擴展:BMP,GIF,JPG,JPEG和PNG。由於#1153,SVG文件被排除在外。
這是一個示例:
import React from 'react' ;
import logo from './logo.png' ; // Tell Webpack this JS file uses this image
console . log ( logo ) ; // /logo.84287d09.png
function Header ( ) {
// Import result is the URL of your image
return < img src = { logo } alt = "Logo" / > ;
}
export default Header ;
這樣可以確保構建項目時,WebPack將正確將圖像移至構建文件夾中,並為我們提供正確的路徑。
這也在CSS中起作用:
. Logo {
background-image : url (. / logo.png);
}
WebPack在CSS中找到所有相對模塊的參考(它們以./
開頭),並用編譯捆綁包的最終路徑代替它們。如果您製作錯別字或意外刪除重要文件,則會看到彙編錯誤,就像導入不存在的JavaScript模塊時一樣。編譯捆綁包中的最終文件名是由WebPack從內容哈希生成的。如果將來文件內容更改,則WebPack將在生產中給它一個不同的名稱,因此您不必擔心資產的長期緩存。
請注意,這也是WebPack的自定義功能。
反應不是必需的,但許多人喜歡它(React Antial使用類似的圖像機制)。
下一部分將描述一種處理靜態資產的替代方法。
注意:此功能可提供
[email protected]
及更高版本。
上面的部分描述了添加SVG文件的一種方法。您也可以直接導入SVG作為React組件。您可以使用兩種方法中的任何一種。在您的代碼中,它看起來像這樣:
import { ReactComponent as Logo } from './logo.svg' ;
const App = ( ) => (
< div >
{ /* Logo is an actual React component */ }
< Logo / >
< / div >
) ;
如果您不想將SVG加載為單獨的文件,這很方便。不要忘記導入中的捲曲牙套! ReactComponent
導入名稱很特別,並告訴創建React應用程序,您需要一個呈現SVG而不是其文件名的React組件。
public
文件夾注意:此功能可提供
[email protected]
及更高版本。
public
文件夾包含HTML文件,因此您可以對其進行調整以設置頁面標題。帶有編譯代碼的<script>
標籤將在構建過程中自動添加到其。
您還可以將其他資產添加到public
文件夾中。
請注意,我們通常鼓勵您import
JavaScript文件中的資產。例如,請參見有關添加樣式表並添加圖像和字體的部分。該機制提供了許多好處:
但是,有一個逃生艙口可以用來在模塊系統外添加資產。
如果將文件放入public
文件夾中,則不會由WebPack處理。取而代之的是,它將被複製到構建文件夾中。要在public
文件夾中參考資產,您需要使用一個稱為PUBLIC_URL
的特殊變量。
內部index.html
,您可以這樣使用:
< link rel =" shortcut icon " href =" %PUBLIC_URL%/favicon.ico " >
%PUBLIC_URL%
前綴只能訪問public
文件夾中的文件。如果您需要使用src
或node_modules
中的文件,則必須在此處複製它,以明確指定您的意圖使該文件成為構建的一部分。
當您運行npm run build
時,創建React App將用正確的絕對路徑替換%PUBLIC_URL%
因此即使您使用客戶端路由或在非根系URL中使用客戶端路由,您的項目也可以使用。
在JavaScript代碼中,您可以使用process.env.PUBLIC_URL
進行類似目的:
render ( ) {
// Note: this is an escape hatch and should be used sparingly!
// Normally we recommend using `import` for getting asset URLs
// as described in “Adding Images and Fonts” above this section.
return < img src = { process . env . PUBLIC_URL + '/img/logo.png' } / > ;
}
請記住這種方法的弊端:
public
文件夾中的任何文件都沒有得到後處理或縮小。public
文件夾通常,我們建議從JavaScript導入樣式表,圖像和字體。 public
文件夾可作為許多不常見情況的解決方法:
manifest.webmanifest
。pace.js
<script>
標籤中。請注意,如果添加聲明全局變量的<script>
,您還需要閱讀有關使用它們的下一部分。
當您在HTML文件中包含一個定義全局變量並嘗試在代碼中使用這些變量之一的腳本時,Linter會抱怨,因為它看不到變量的定義。
您可以通過從window
對像明確讀取全局變量來避免這種情況,例如:
const $ = window . $ ;
這很明顯您是故意使用全局變量的,而不是由於錯別字。
另外,您可以強迫Linter在其後通過添加// eslint-disable-line
來忽略任何線路。
您不必將ReactStrap與React一起使用,但它是將引導程序與React應用集成的流行庫。如果需要,可以按照以下步驟將其與Create React應用程序集成:
從NPM安裝ReactStrap和Bootstrap。 ReactStrap不包括Bootstrap CSS,因此也需要安裝:
npm install --save reactstrap bootstrap@4
或者,您可以使用yarn
:
yarn add bootstrap@4 reactstrap
在您的src/index.js
文件的開頭中導入Bootstrap CSS和Bootstrap主題CSS:
import 'bootstrap/dist/css/bootstrap.css' ;
// Put any other imports below so that CSS from your
// components takes precedence over default styles.
導入src/App.js
文件或您的自定義組件文件中所需的ReactStrap組件:
import { Button } from 'reactstrap' ;
現在,您準備在渲染方法中定義的組件層次結構中使用導入的ReactStrap組件。這是使用ReactStrap的示例App.js
重做。
注意:此功能可提供
[email protected]
及更高版本。
有時,您可能需要調整自舉的視覺樣式(或等效軟件包)。
從[email protected]
開始,您可以導入.scss
文件。這使得可以將軟件包的內置SASS變量用於全局樣式首選項。
要自定義Bootstrap,請創建一個名為src/custom.scss
(或類似)的文件,然後導入Bootstrap源樣式表。在導入文件之前添加任何覆蓋。您可以為可用變量的名稱引用Bootstrap的文檔。
// Override default variables before the import
$body-bg : #000 ;
// Import Bootstrap and its default variables
@import ' ~bootstrap/scss/bootstrap.scss ' ;
注意:您必須從
node_modules
導入~
,如上所述。
最後,在src/index.js
文件的開頭中導入新創建的.scss
文件,而不是默認的bootstrap .css
:
import './custom.scss' ;
Flow是一種靜態類型的檢查器,可幫助您使用更少的錯誤編寫代碼。如果您是此概念的新手,請查看此介紹,以使用JavaScript中的靜態類型。
開箱即用的Flow Work的最新版本使用創建React App Projects。
要添加到創建React App項目的流程,請按照以下步驟:
npm install --save flow-bin
(或yarn add flow-bin
)。"flow": "flow"
添加到您的package.json
的scripts
部分。npm run flow init
(或yarn flow init
),以在根目錄中創建.flowconfig
文件。// @flow
到您要輸入檢查的任何文件(例如, src/App.js
)。現在,您可以運行npm run flow
(或yarn flow
)來檢查文件是否類型錯誤。您可以選擇使用IDE之類的核素來獲得更好的集成體驗。將來,我們計劃將其集成到創建React應用程序中。
要了解有關流的更多信息,請查看其文檔。
繼電器是構建由GraphQl供電的數據驅動的反應應用程序的框架。當前的接力賽候選人使用Babel Macros開箱即用的Create React App Projects使用。只需按照繼電器文檔中佈置的項目設置您的項目,然後確保您擁有提供宏的Babel插件的版本。
要添加它,請運行:
npm install --save --dev babel-plugin-relay@dev
或者,您可以使用yarn
:
yarn upgrade babel-plugin-relay@dev
然後,無論何處使用graphql
模板標籤,都會導入宏:
import graphql from 'babel-plugin-relay/macro' ;
// instead of:
// import { graphql } from "babel-plugin-relay"
graphql `
query UserQuery {
viewer {
id
}
}
` ;
要了解有關繼電器的更多信息,請查看其文檔。
Create React應用程序沒有規定特定的路由解決方案,但React路由器是最受歡迎的路由器。
要添加它,請運行:
npm install --save react-router-dom
或者,您可以使用yarn
:
yarn add react-router-dom
要嘗試一下,請在src/App.js
中刪除所有代碼,然後用其網站上的任何示例替換它。基本示例是一個好地方。
請注意,在部署應用程序之前,您可能需要配置生產服務器以支持客戶端路由。
注意:此功能可提供
[email protected]
及更高版本。
您的項目可以消耗在您的環境中聲明的變量,就好像它們是在JS文件中本地聲明的一樣。默認情況下,您將為您定義NODE_ENV
,以及以REACT_APP_
開頭的任何其他環境變量。
環境變量在構建時間內嵌入。由於Create React應用程序會產生靜態HTML/CSS/JS捆綁包,因此無法在運行時讀取它們。要在運行時讀取它們,您需要將HTML加載到服務器上的內存中,並在運行時替換佔位符,就像此處所述。另外,您可以隨時更改服務器上的應用程序。
注意:您必須創建以
REACT_APP_
開頭的自定義環境變量。除了NODE_ENV
之外,所有其他變量都將被忽略,以避免在計算機上意外暴露出可能具有相同名稱的私鑰。更改任何環境變量將需要您在運行開發服務器時重新啟動。
這些環境變量將在process.env
上為您定義。例如,具有名為REACT_APP_SECRET_CODE
的環境變量將在您的js中以process.env.REACT_APP_SECRET_CODE
形式公開。
還有一個特殊的內置環境變量,稱為NODE_ENV
。您可以從process.env.NODE_ENV
讀取它。當您運行npm start
時,它始終等於'development'
,當您運行npm test
時,它始終等於'test'
,當您運行npm run build
以製造生產捆綁包時,它始終等於'production'
。您不能手動覆蓋NODE_ENV
。這樣可以防止開發人員意外將緩慢的開發構建部署到生產中。
這些環境變量可用於根據部署項目的位置或消耗在版本控制之外的敏感數據的何處來顯示信息很有用。
首先,您需要定義環境變量。例如,假設您想消耗<form>
內部環境中定義的秘密:
render ( ) {
return (
< div >
< small > You are running this application in < b > { process . env . NODE_ENV } < / b > mode. < / small >
< form >
< input type = "hidden" defaultValue = { process . env . REACT_APP_SECRET_CODE } / >
< / form >
< / div >
) ;
}
在構建過程中, process.env.REACT_APP_SECRET_CODE
將被REACT_APP_SECRET_CODE
環境變量的當前值替換。請記住, NODE_ENV
變量將自動為您設置。
當您將應用程序加載到瀏覽器中並檢查<input>
時,您會看到其值設置為abcdef
,並且BOLD文本將顯示使用npm start
時提供的環境:
< div >
< small > You are running this application in < b > development </ b > mode. </ small >
< form >
< input type =" hidden " value =" abcdef " />
</ form >
</ div >
上面的形式正在尋找一個從環境中尋找稱為REACT_APP_SECRET_CODE
的變量。為了消耗此值,我們需要在環境中定義它。這可以使用兩種方法完成:在您的外殼或.env
文件中。在接下來的幾節中描述了這兩種方式。
訪問NODE_ENV
也可用於有條件地執行操作:
if ( process . env . NODE_ENV !== 'production' ) {
analytics . disable ( ) ;
}
當您使用npm run build
編譯應用程序時,縮小步驟將剝離此條件,並且所得的捆綁包將較小。
注意:此功能可提供
[email protected]
及更高版本。
您還可以在public/index.html
中以REACT_APP_
開頭的環境變量訪問環境變量。例如:
< title > %REACT_APP_WEBSITE_NAME% </ title >
請注意,上面的警告適用:
NODE_ENV
和PUBLIC_URL
)之外,變量名稱必須以REACT_APP_
開頭才能工作。定義環境變量在OS之間可能會有所不同。同樣重要的是要知道這種方式在殼會議的生活中是暫時的。
set " REACT_APP_SECRET_CODE = abcdef " && npm start
(注意:需要圍繞變量分配的引號才能避免落後的空格。)
( $ env: REACT_APP_SECRET_CODE = " abcdef " ) -and (npm start)
REACT_APP_SECRET_CODE=abcdef npm start
.env
中添加開發環境變量注意:此功能可提供
[email protected]
及更高版本。
要定義永久環境變量,請在項目根部創建一個名為.env
的文件:
REACT_APP_SECRET_CODE=abcdef
注意:您必須創建以
REACT_APP_
開頭的自定義環境變量。除了NODE_ENV
之外,所有其他變量都將被忽略,以避免在計算機上意外暴露出可能具有相同名稱的私鑰。更改任何環境變量將需要您在運行開發服務器時重新啟動。
.env
文件應將其檢查到源控件中(排除.env*.local
)。
.env
文件?注意:此功能可提供
[email protected]
及更高版本。
.env
:默認。.env.local
:本地覆蓋。此文件已為除測試外的所有環境加載。.env.development
.env.development.local
左側的文件比右邊的文件更優先:
npm start
: .env.development.local
, .env.development
, .env.local
, .env
npm run build
: .env.production.local
, .env.production
, .env.local
, .env
npm test
: .env.test.local
, .env.test
, .env
(note .env.local
缺少)如果機器未明確設置它們,這些變量將充當默認值。
有關更多詳細信息,請參考Dotenv文檔。
注意:如果您定義了開發環境變量,則您的CI和/或託管平台很可能也需要定義。諮詢他們的文檔如何執行此操作。例如,請參閱Travis CI或Heroku的文檔。
.env
中擴展環境變量注意:此功能可提供
[email protected]
及更高版本。
擴展機器上的變量已在.env
文件中使用(使用dotenv-expand)。
例如,獲取環境變量npm_package_version
:
REACT_APP_VERSION=$npm_package_version
# also works:
# REACT_APP_VERSION=${npm_package_version}
或將變量本地擴展到當前.env
文件:
DOMAIN=www.example.com
REACT_APP_FOO=$DOMAIN/foo
REACT_APP_BAR=$DOMAIN/bar
一些受歡迎的圖書館在其文檔中使用裝飾商。
目前,創建React應用程序故意不支持Decorator語法,因為:
但是,在許多情況下,您可以在沒有裝飾器的情況下重寫基於裝飾的代碼。
請參考這兩個線程以供參考:
當規格發展到穩定階段時,創建React應用程序將添加裝飾器支持。
React沒有規定數據獲取的特定方法,但是人們通常使用Axios之類的庫或瀏覽器提供的fetch()
API。
全局fetch
功能使您可以輕鬆地提出AJAX請求。它以URL為輸入,並返回解決Response
對象的Promise
。您可以在此處找到有關fetch
的更多信息。
一個承諾代表了異步操作的最終結果,您可以在此處和此處找到有關承諾的更多信息。 Axios和fetch()
都在引擎蓋下使用承諾。您也可以使用async / await
語法來減少回調嵌套。
確保您的目標受眾的瀏覽器中有fetch()
API和承諾。例如,Internet Explorer中的支持需要多填充。
您可以在React網站上的常見問題解答條目中從React組件中提出AJAX請求的更多信息。
這些教程將幫助您將應用程序與在另一個端口上運行的API後端集成在一起,並使用fetch()
訪問它。
查看本教程。您可以在此處找到同伴GitHub存儲庫。
查看本教程。您可以在此處找到同伴GitHub存儲庫。
API平台是一個旨在構建API驅動項目的框架。它允許在幾分鐘內創建HyperMedia和GraphQl API。它配有官方的漸進式Web應用程序生成器以及動態管理接口,均為Create React應用程序構建。查看本教程。
注意:此功能可提供
[email protected]
及更高版本。
人們經常從同一主機和端口與後端實施服務前端React應用程序。
例如,在部署應用程序後,生產設置可能看起來像這樣:
/ - static server returns index.html with React app
/todos - static server returns index.html with React app
/api/todos - server handles any /api/* requests using the backend implementation
不需要這種設置。但是,如果您確實有這樣的設置,則很方便地編寫諸如fetch('/api/todos')
之類的請求,而不必擔心開發過程中將它們重定向到另一個主機或端口。
要告訴開發服務器以代理開發中的API服務器的任何未知請求,請在您的package.json
中添加proxy
字段。JSON,例如:
"proxy" : "http://localhost:4000" ,
這樣,當您在開發中fetch('/api/todos')
時,開發服務器將認識到它不是靜態資產,並且會將您的請求委託給http://localhost:4000/api/todos
作為後備。開發服務器只會嘗試在其Accept
標頭中未經text/html
發送請求到代理。
方便地,這避免了CORS問題和類似此類的錯誤消息:
Fetch API cannot load http://localhost:4000/api/todos. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
請記住, proxy
僅在開發中具有效果( npm start
),並且由您確保/api/todos
之類的URL指向生產中正確的東西。您不必使用/api
前綴。沒有text/html
接受標頭的任何未識別的請求將被重定向到指定的proxy
。
proxy
選項支持HTTP,HTTP和WebSocket連接。
如果proxy
選項對您來說還不夠靈活,或者您可以:
啟用proxy
選項時,您會選擇更嚴格的主機檢查。這是必要的,因為將後端留給遠程主機會使您的計算機容易受到DNS重新攻擊的攻擊。本文和本問題都解釋了這個問題。
在localhost
上開發時,這不應影響您,但是如果您在此處所描述的遠程開發,則在啟用proxy
選項後會在瀏覽器中看到此錯誤:
無效的主機標頭
要圍繞它,您可以在項目的根源中指定您的公共開發.env.development
。
HOST=mypublicdevhost.com
如果您現在重新啟動開發服務器並從指定的主機加載應用程序,則應起作用。
如果您仍在遇到問題,或者您正在使用更奇特的環境(例如雲編輯器),則可以通過在.env.development.local
中添加一條線來完全繞過主機檢查。請注意,這很危險,並將您的計算機暴露於惡意網站上的遠程代碼執行:
# NOTE: THIS IS DANGEROUS!
# It exposes your machine to attacks from the websites you visit.
DANGEROUSLY_DISABLE_HOST_CHECK=true
我們不建議這種方法。
注意:此功能可提供
[email protected]
及更高版本。
如果proxy
選項對您來說不夠靈活,則可以直接訪問Express App實例並連接您自己的代理中間件。
您可以將此功能與package.json
中的proxy
屬性一起使用,但是建議您將所有邏輯合併到src/setupProxy.js
中。
首先,使用NPM或紗線安裝http-proxy-middleware
:
$ npm install http-proxy-middleware --save
$ # or
$ yarn add http-proxy-middleware
接下來,創建src/setupProxy.js
並將以下內容放入其中:
const proxy = require ( 'http-proxy-middleware' ) ;
module . exports = function ( app ) {
// ...
} ;
您現在可以按照自己的意願註冊代理!這是使用上述http-proxy-middleware
示例:
const proxy = require ( 'http-proxy-middleware' ) ;
module . exports = function ( app ) {
app . use ( proxy ( '/api' , { target : 'http://localhost:5000/' } ) ) ;
} ;
注意:您無需任何地方導入此文件。啟動開發服務器時,它會自動註冊。
注意:此文件僅支持Node的JavaScript語法。請確保僅使用支持的語言功能(即不支持Flow,ES模塊等)。
注意:傳遞通往代理功能的路徑使您可以在路徑上使用球形和/或模式匹配,這比快速路由匹配更靈活。
注意:此功能可提供
[email protected]
及更高版本。
您可能要求開發服務器通過HTTPS提供頁面。一種可能有用的特殊情況是,當該API服務器本身使用HTTPS時,將“代理”功能使用“代理”功能向API服務器發出。
為此,請將HTTPS
環境變量設置為true
,然後像往常一樣在npm start
時啟動Dev Server:
set HTTPS = true && npm start
(注意:缺乏空格是故意的。)
( $ env: HTTPS = $true ) -and (npm start)
HTTPS=true npm start
請注意,服務器將使用自簽名的證書,因此您的Web瀏覽器在訪問頁面時幾乎肯定會顯示警告。
<meta>
標籤由於Create React App不支持服務器渲染,因此您可能想知道如何製作<meta>
標籤動態並反映當前的URL。為了解決這個問題,我們建議將佔位符添加到HTML中,因此:
<!doctype html >
< html lang =" en " >
< head >
< meta property =" og:title " content =" __OG_TITLE__ " >
< meta property =" og:description " content =" __OG_DESCRIPTION__ " >
然後,在服務器上,無論您使用哪種後端,都可以將index.html
讀取到內存中,然後替換__OG_TITLE__
, __OG_DESCRIPTION__
和任何其他具有值的其他佔位符,具體取決於當前URL。只需確保消毒並逃脫插值值,以便它們可以安全地嵌入HTML!
如果您使用節點服務器,甚至可以在客戶端和服務器之間共享路由匹配邏輯。但是,在簡單的情況下,重複它也可以很好地工作。
如果您使用靜態託管提供商託管build
,則可以使用React-Snapshot或React-Snap在您的應用程序中為每個路線或相對鏈接生成HTML頁面。然後,當JavaScript束加載時,這些頁面將無縫變得活躍或“水合”。
也有機會在靜態託管之外使用它,以便在生成和緩存路線時承受服務器的壓力。
預渲染的主要好處是,您可以通過HTML有效載荷獲得每個頁面的核心內容,而沒有成功下載JavaScript捆綁包。這也增加了您應用程序的每條路線的可能性。
您可以在此處閱讀有關零配置預先渲染(也稱為快照)的更多信息。
與上一節類似,您可以將一些注入全局變量的HTML留在HTML中:
< ! doctype html >
< html lang = "en" >
< head >
< script >
window.SERVER_DATA = __SERVER_DATA__;
< / script >
然後,在服務器上,您可以在發送響應之前先用真實數據的json替換__SERVER_DATA__
。然後,客戶端代碼可以讀取window.SERVER_DATA
來使用它。在將JSON發送給客戶端之前,請確保對其進行消毒,因為它使您的應用程序容易受到XSS攻擊的影響。
注意:此功能可提供
[email protected]
及更高版本。
閱讀遷移指南,以了解如何在較舊的項目中啟用它!
Create React App使用開玩笑作為其測試跑者。為了為這種整合做準備,我們對開玩笑進行了重大改造,因此,如果您幾年前聽到有關它的壞事,請再次嘗試。
Jest是基於節點的跑步者。這意味著測試始終在節點環境中進行,而不是在真實的瀏覽器中進行。這使我們可以實現快速的迭代速度並防止片狀。
雖然Jest提供了JSDON的瀏覽器Globals,例如window
,但它們只是真正的瀏覽器行為的近似值。開玩笑旨在用於您的邏輯和組件的單位測試,而不是DOM Quirks。
我們建議您使用單獨的工具進行瀏覽器端到端測試。它們超出了創建React應用程序的範圍。
Jest將尋找具有以下任何流行命名約定的測試文件:
__tests__
文件夾中的.js
後綴的文件。.test.js
後綴的文件。.spec.js
後綴的文件。 .test.js
/ .spec.js
文件(或__tests__
文件夾)位於src
頂級文件夾下的任何深度。
我們建議將測試文件(或__tests__
文件夾)放在他們正在測試的代碼旁邊,以使相對導入看起來更短。例如,如果App.test.js
和App.js
在同一文件夾中,則測試只需要從import App from './App'
而不是較長的相對路徑。託管還有助於在大型項目中更快地找到測試。
當您運行npm test
時,JEST將在手錶模式下啟動。每次保存文件時,它都會重新運行測試,就像npm start
一樣,重新編譯代碼。
觀察者包括一個交互式命令行界面,具有運行所有測試或專注於搜索模式的能力。它是通過這種方式設計的,以便您可以保持打開狀態並享受快速重新運行。您可以從“觀看用法”中學習命令,請注意,觀察者每次運行後都會打印出來:
默認情況下,當您運行npm test
時,JEST只會運行與上次提交以來更改的文件相關的測試。這是一種優化,旨在使您的測試快速進行,而不管您有多少個測試。但是,它假設您通常不會提交未通過測試的代碼。
Jest將始終明確地提到它僅運行與上次提交以來更改的文件相關的測試。您也可以在手錶模式下按a
迫使Jest進行所有測試。
開玩笑將始終在連續集成服務器上或項目不在git或mercurial存儲庫中。
要創建測試,請添加it()
(或test()
)塊,其中具有測試名稱及其代碼。您可以選擇將它們包裝在邏輯分組中的describe()
塊中,但這既不需要也不建議。
Jest提供了一個內置的expect()
全局函數來做出斷言。基本測試看起來像這樣:
import sum from './sum' ;
it ( 'sums numbers' , ( ) => {
expect ( sum ( 1 , 2 ) ) . toEqual ( 3 ) ;
expect ( sum ( 2 , 2 ) ) . toEqual ( 4 ) ;
} ) ;
JEST支持的所有expect()
匹配者在此處進行了廣泛的記錄。
您也可以使用jest.fn()
和expect(fn).toBeCalled()
創建“間諜”或模擬功能。
組件測試技術有廣泛的範圍。它們的範圍從“煙霧測試”驗證,驗證組件是否不投擲,淺渲染和測試某些輸出,到完整的渲染和測試組件生命週期和狀態變化。
不同的項目根據組件變化的頻率以及所包含多少邏輯選擇不同的測試權衡。如果您尚未決定測試策略,我們建議您從為您的組件創建簡單的煙霧測試開始:
import React from 'react' ;
import ReactDOM from 'react-dom' ;
import App from './App' ;
it ( 'renders without crashing' , ( ) => {
const div = document . createElement ( 'div' ) ;
ReactDOM . render ( < App / > , div ) ;
} ) ;
該測試將安裝一個組件,並確保其在渲染過程中不會投擲。像這樣的測試提供了很大的價值,因此它們作為起點很棒,這是您在src/App.test.js
中找到的測試。
當您遇到由變化的組件引起的錯誤時,您將獲得更深入的了解,其中哪些部分值得在應用程序中進行測試。這可能是引入更具體測試的好時機,主張特定的預期產出或行為。
如果您想與它們渲染的兒童組件隔離測試組件,我們建議使用shallow()
呈現API的API。要安裝它,請運行:
npm install --save enzyme enzyme-adapter-react-16 react-test-renderer
或者,您可以使用yarn
:
yarn add enzyme enzyme-adapter-react-16 react-test-renderer
在酶3中,您將需要安裝酶以及與您使用的React版本相對應的適配器。 (上面的示例使用適配器進行react 16。
適配器還需要在您的全局設置文件中進行配置:
src/setupTests.js
import { configure } from 'enzyme' ;
import Adapter from 'enzyme-adapter-react-16' ;
configure ( { adapter : new Adapter ( ) } ) ;
注意:請記住,如果您決定在創建
src/setupTests.js
之前“彈出”,則結果package.json
文件將不包含對其的任何引用。在此處閱讀以了解彈出後如何添加此內容。
現在您可以用它進行煙霧測試:
import React from 'react' ;
import { shallow } from 'enzyme' ;
import App from './App' ;
it ( 'renders without crashing' , ( ) => {
shallow ( < App / > ) ;
} ) ;
與以前使用ReactDOM.render()
的煙霧測試不同,此測試僅渲染<App>
,並且不會更深。例如,即使<App>
本身會呈現一個投擲的<Button>
,此測試也會通過。淺渲染非常適合隔離的單元測試,但是您可能仍需要創建一些完整的渲染測試以確保組件正確集成。酶支持使用mount()
完全渲染,您也可以將其用於測試狀態變化和組件生命週期。
您可以閱讀酶文檔以獲取更多測試技術。酶文檔使用Chai和Sinon進行斷言,但您不必使用它們,因為JEST為SPIE提供了內置的expect()
和jest.fn()
。
這是酶文檔中的一個示例,該酶斷言特定的輸出,重寫以使用開玩笑的匹配器:
import React from 'react' ;
import { shallow } from 'enzyme' ;
import App from './App' ;
it ( 'renders welcome message' , ( ) => {
const wrapper = shallow ( < App / > ) ;
const welcome = < h2 > Welcome to React < / h2 > ;
// expect(wrapper.contains(welcome)).toBe(true);
expect ( wrapper . contains ( welcome ) ) . toEqual ( true ) ;
} ) ;
所有的玩笑匹配者都在此處進行了廣泛的記錄。
但是,如果您願意,您可以使用像Chai這樣的第三方斷言庫,如下所述。
此外,您可能會發現開玩笑的酶有助於使用可讀的匹配器簡化測試。以上contains
代碼可以用開玩笑的酶編寫。
expect ( wrapper ) . toContainReact ( welcome ) ;
要啟用此功能,請安裝jest-enzyme
:
npm install --save jest-enzyme
或者,您可以使用yarn
:
yarn add jest-enzyme
在src/setupTests.js
中導入它,以使其匹配器在每個測試中可用:
import 'jest-enzyme' ;
我們建議您將expect()
用於主張,而jest.fn()
用於間諜。如果您對它們有問題,請針對Jest提出這些問題,我們將修復它們。我們打算繼續使它們更好地進行反應,例如支持jsx的相當印刷元素。
但是,如果您習慣了其他庫,例如Chai和Sinon,或者使用要移植的現有代碼,則可以正常地導入它們:
import sinon from 'sinon' ;
import { expect } from 'chai' ;
然後像往常一樣在測試中使用它們。
注意:此功能可提供
[email protected]
及更高版本。
如果您的應用程序使用您需要在測試中嘲笑的瀏覽器API,或者在運行測試之前只需要全局設置,請在項目中添加src/setupTests.js
。它將在運行測試之前自動執行。
例如:
src/setupTests.js
const localStorageMock = {
getItem : jest . fn ( ) ,
setItem : jest . fn ( ) ,
clear : jest . fn ( ) ,
} ;
global . localStorage = localStorageMock ;
注意:請記住,如果您決定在創建
src/setupTests.js
之前“彈出”,setupTestFrameworkScriptFile
結果package.json
。如下所示:
"jest" : { // ... "setupTestFrameworkScriptFile" : "<rootDir>/src/setupTests.js" }
您可以將it()
替換為xit()
,以暫時將測試排除在執行中。
同樣, fit()
可讓您專注於特定的測試,而無需進行任何其他測試。
Jest具有一個集成的覆蓋記者,可與ES6配合使用,不需要配置。
運行npm test -- --coverage
(在中間注意額外--
額外),以包括這樣的覆蓋範圍報告:
請注意,測試的覆蓋範圍較慢,因此建議將其與普通工作流程分開運行。
可以通過將以下任何支持的密鑰添加到軟件包中的jest.json中的jest config。
支持的替代:
collectCoverageFrom
coverageReporters
coverageThreshold
snapshotSerializers
示例軟件包。
{
"name" : " your-package " ,
"jest" : {
"collectCoverageFrom" : [
" src/**/*.{js,jsx} " ,
" !<rootDir>/node_modules/ " ,
" !<rootDir>/path/to/dir/ "
],
"coverageThreshold" : {
"global" : {
"branches" : 90 ,
"functions" : 90 ,
"lines" : 90 ,
"statements" : 90
}
},
"coverageReporters" : [ " text " ],
"snapshotSerializers" : [ " my-serializer-module " ]
}
}
默認情況下, npm test
將使用Interactive CLI運行觀察者。但是,您可以強迫它運行一次測試,並通過設置稱為CI
環境變量來完成該過程。
默認情況下,使用npm run build
Linter警告創建應用程序的構建時。像npm test
一樣,您可以通過設置環境變量CI
強迫構建來執行襯裡警告檢查。如果遇到任何警告,則構建失敗。
流行的CI服務器默認情況下已經設置了環境變量CI
,但是您也可以自己執行此操作:
.travis.yml
文件添加到您的git存儲庫中。 language: node_js
node_js:
- 8
cache:
directories:
- node_modules
script:
- npm run build
- npm test
請按照本文使用Create React App Project設置CircleCi。
set CI = true && npm test
set CI = true && npm run build
(注意:缺乏空格是故意的。)
( $ env: CI = $true ) -and (npm test)
( $ env: CI = $true ) -and (npm run build)
CI=true npm test
CI=true npm run build
測試命令將迫使玩笑一次進行測試,而不是啟動觀察者。
如果您發現自己經常在開發中進行此操作,請提出一個問題來告訴我們您的用例,因為我們希望使Watcher獲得最佳體驗,並願意更改其工作方式以適應更多的工作流程。
構建命令將檢查是否有襯裡警告,如果發現有任何警告,則會失敗。
如果您知道您的測試都不取決於JSDOM,則可以安全設置--env=node
,並且您的測試將更快地運行:
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
- "test": "react-scripts test"
+ "test": "react-scripts test --env=node"
為了幫助您下定決心,以下是需要JSDOM的API列表:
window
和document
等任何瀏覽器全球範圍ReactDOM.render()
TestUtils.renderIntoDocument()
(上述快捷方式)mount()
相比之下,以下API不需要JSDOM :
TestUtils.createRenderer()
(淺渲染)shallow()
最後,快照測試也不需要JSDOM。
快照測試是Jest的一個功能,它會自動生成組件的文本快照並將其保存在磁盤上,因此,如果UI輸出更改,則不會在組件輸出上手動編寫任何斷言而通知您。閱讀有關快照測試的更多信息。
如果您使用Visual Studio代碼,則有一個開玩笑的擴展名,可與Create Apple一起使用。使用文本編輯器時,這提供了許多類似IDE的功能:顯示潛在的失敗消息內聯的測試狀態,自動啟動和停止觀察者,並提供一鍵式快照更新。
有多種方法可以為您的玩笑測試設置調試器。我們涵蓋Chrome和Visual Studio代碼中的調試。
注意:調試測試需要節點8或更高。
將以下內容添加到您項目package.json
中的scripts
部分。
"scripts" : {
"test:debug" : " react-scripts --inspect-brk test --runInBand "
}
位置debugger;
任何測試和運行中的語句:
$ npm run test:debug
這將開始進行開玩笑的測試,但在執行之前暫停,以允許調試器附加到該過程。
在Chrome中打開以下內容
about:inspect
打開該鏈接後,將顯示Chrome開發人員工具。選擇您的過程中的inspect
,將在React腳本的第一行中設置斷點(這只是為了讓您有時間打開開發人員工具並防止JEST在您有時間之前執行)。單擊屏幕右上方的“播放”按鈕的按鈕繼續執行。當Jest執行包含Debugger語句的測試時,執行將暫停,您可以檢查當前範圍並調用堆棧。
注意: - runinband CLI選項可確保在同一過程中開玩笑地運行測試,而不是為單個測試產卵過程。通常,開玩笑平行於測試跨過程運行,但很難同時調試許多過程。
開箱即用的開箱即用調試JEST測試。
使用以下launch.json
配置文件:
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug CRA Tests",
"type": "node",
"request": "launch",
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/react-scripts",
"args": [
"test",
"--runInBand",
"--no-cache"
],
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
}
]
}
通常,在應用程序中,您有很多UI組件,並且每個UI組件都有許多不同的狀態。例如,一個簡單的按鈕組件可能具有以下狀態:
通常,很難看到這些狀態而不運行示例應用程序或一些示例。
Create React App默認不包含任何工具,但是您可以輕鬆地將故事書添加到React(Source)或React Styleguidist(源)中。這些是第三方工具,可讓您開發組件,並與您的應用程序孤立地看到其所有狀態。
您還可以將故事書或樣式指南部署為靜態應用。這樣,團隊中的每個人都可以在不啟動後端服務器或在應用程序中創建帳戶的情況下查看和查看UI組件的不同狀態。
Storybook是React UI組件的開發環境。它允許您瀏覽組件庫,查看每個組件的不同狀態,並進行交互開發和測試組件。
首先,全球安裝以下NPM軟件包:
npm install -g @storybook/cli
然後,在應用程序目錄中運行以下命令:
getstorybook
之後,請按照屏幕上的說明進行操作。
了解有關React Storybook的更多信息:
Styleguidist結合了樣式指南,其中所有組件都呈現在單個頁面上,其中包含其道具文檔和用法示例,以及一個與Storybook類似的隔離組件的環境。在StyleGuidist中,您可以在Markdown中編寫示例,其中每個代碼段都被渲染為現場編輯的操場。
首先,安裝StyleGuidist:
npm install --save react-styleguidist
或者,您可以使用yarn
:
yarn add react-styleguidist
然後,將這些腳本添加到您的package.json
:
"scripts": {
+ "styleguide": "styleguidist server",
+ "styleguide:build": "styleguidist build",
"start": "react-scripts start",
然後,在應用程序目錄中運行以下命令:
npm run styleguide
之後,請按照屏幕上的說明進行操作。
了解有關React Stylegidist的更多信息:
Create React應用程序沒有提供任何內置功能,可以將組件發佈到NPM。如果您準備從項目中提取組件,以便其他人可以使用它,我們建議將其移至項目外的單獨目錄,然後使用NWB之類的工具來準備出版。
生產構建具有生成一流的漸進式Web應用所需的所有工具,但是離線/高速緩存優先的行為僅選擇加入。默認情況下,構建過程將生成服務工作者文件,但不會註冊,因此它不會控制您的生產Web應用程序。
為了選擇進入離線第一行為,開發人員應在其src/index.js
文件中查找以下內容:
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: http://bit.ly/CRA-PWA
serviceWorker . unregister ( ) ;
正如評論所述,將serviceWorker.unregister()
轉換為serviceWorker.register()
將選擇您使用服務工作者。
離線漸進式網絡應用程序比傳統網頁更快,更可靠,並提供引人入勝的移動體驗:
但是,它們可以使調試部署更具挑戰性,因此,從Create React App 2開始,服務工作人員選擇加入。
workbox-webpack-plugin
已集成到生產配置中,它將負責生成一個服務工作者文件,該文件將自動腐蝕所有本地資產,並在部署更新時使其保持最新狀態。服務工作者將使用緩存優先的策略來處理所有本地資產請求,包括對HTML的導航請求,以確保您的Web應用程序始終快速,即使在慢速或不可靠的網絡上也是如此。
如果您確實決定選擇進入服務工作者註冊,請考慮以下內容:
服務工作人員需要HTTP,儘管為了促進本地測試,但該政策不適用於localhost
。如果您的生產Web服務器不支持HTTP,則服務工作者註冊將失敗,但是您的Web應用程序的其餘部分將保持功能。
較舊的Web瀏覽器中不支持服務工作人員。服務工作者註冊不會嘗試缺乏支持的瀏覽器。
服務工作者僅在生產環境中啟用,例如npm run build
的輸出。建議您不要在開發環境中啟用離線服務工作者,因為當使用以前的緩存資產時,它可能會導致挫敗感,並且不包括您在當地進行的最新更改。
如果您需要在本地測試您的離線優先服務工作者,請構建應用程序(使用npm run build
),然後從構建目錄運行簡單的HTTP服務器。運行構建腳本後, create-react-app
將提供一種指令,以一種在本地測試生產構建的方法,並且部署說明具有使用其他方法的說明。請務必始終使用隱身窗口,以避免使用瀏覽器緩存並發症。
用戶並不總是熟悉離線優先的Web應用程序。讓用戶知道服務工作者何時完成填充您的緩存可能會很有用(顯示“此Web應用程序脫機!”消息),也讓他們知道服務工作者何時提取了最新的更新下次他們加載頁面時(顯示“可用新內容;請刷新”。消息)。目前,顯示此消息是向開發人員練習的,但是作為起點,您可以使用src/registerServiceWorker.js
中包含的邏輯,該邏輯演示了哪些服務工作者的生命週期事件來聆聽以檢測每種情況,並且默認情況下,只需將適當的消息記錄到JavaScript控制台即可。
默認情況下,生成的服務工作者文件將不會攔截或緩存任何交叉原始流量,例如HTTP API請求,圖像或從其他域中加載的嵌入。
默認配置包括位於public/manifest.json
上的Web應用清單,您可以使用特定於Web應用程序的詳細信息進行自定義。
當用戶使用Chrome或Firefox上的Android上的Chrome或Firefox將Web應用程序添加到HOMESCREEN時, manifest.json
中的元數據。JSON確定顯示Web應用程序時要使用的圖標,名稱和品牌顏色。 Web應用清單指南提供了更多有關每個字段的含義以及您的自定義如何影響用戶體驗的上下文。
添加到HomeScreen的漸進式Web應用程序在有活躍的服務工作者時將更快地加載並脫機。話雖這麼說,無論您是否選擇加入服務工作者註冊,Web應用程序清單中的元數據仍將被使用。
源地圖Explorer使用源地圖分析JavaScript捆綁包。這可以幫助您了解代碼膨脹的來源。
要將源地圖Explorer添加到創建React App項目中,請按照以下步驟:
npm install --save source-map-explorer
或者,您可以使用yarn
:
yarn add source-map-explorer
然後在package.json
中,將以下行添加到scripts
:
"scripts": {
+ "analyze": "source-map-explorer build/static/js/main.*",
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
然後分析捆綁包運行生產構建,然後運行分析腳本。
npm run build
npm run analyze
npm run build
通過您的應用程序的生產構建創建一個build
目錄。設置您喜歡的http服務器/static/js/main.<hash>.js
文件。
對於使用節點的環境,處理此操作的最簡單方法是安裝服務並讓其處理其餘部分:
npm install -g serve
serve -s build
上面顯示的最後一個命令將在端口5000上為您的靜態站點提供服務。像服務的許多內部設置一樣,可以使用-p
或--port
標誌調整端口。
運行此命令以獲取可用選項的完整列表:
serve -h
您不一定需要靜態服務器來在生產中運行創建React App項目。它的工作原理同樣可以整合到現有動力學中。
這是使用節點和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完全是平台 - 不可思議的,因此無需明確使用節點。
帶有靜態資產的build
文件夾是Create React應用程序產生的唯一輸出。
但是,如果您使用客戶端路由,這還不夠。如果您想在單頁應用中支持/todos/42
之類的URL,請閱讀下一節。
如果您使用在引擎蓋下使用HTML5 pushState
歷史記錄API的路由器(例如,帶有browserHistory
的React路由器),許多靜態文件服務器將失敗。例如,如果您使用/todos/42
路由的React路由器,則開發服務器將適當地響應localhost:3000/todos/42
,但是如上所述的Express為生產構建服務不會。
這是因為當A /todos/42
有一個新的頁面加載時,服務器會尋找文件build/todos/42
,但找不到它。需要配置服務器,以通過服務index.html
響應/todos/42
的請求。例如,我們可以修改上面的明確示例,以服務於任何未知路徑: index.html
:
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'));
});
如果您使用的是Apache HTTP服務器,則需要在看起來像這樣的public
文件夾中創建一個.htaccess
文件:
Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]
運行npm run build
時,它將被複製到build
文件夾。
如果您使用的是Apache Tomcat,則需要按照此堆棧溢出答案。
現在,對/todos/42
請求將在開發和生產中正確處理。
在生產構建中,當您選擇入門時,服務工作者將自動處理所有導航請求,例如/todos/42
,通過提供您的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 SWPreachePlugin
configuration.
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" : "." ,
By default, Create React App produces a build assuming your app is hosted at the server root.
To override this, specify the homepage
in your package.json
, for example:
"homepage" : "http://mywebsite.com/relativepath" ,
This will let Create React App correctly infer the root path to use in the generated HTML file.
Note : If you are using react-router@^4
, you can root <Link>
s using the basename
prop on any <Router>
.
更多信息在這裡。
例如:
< BrowserRouter basename = "/calendar" / >
< Link to = "/today" / > // renders <a href="/calendar/today">
注意:此功能可提供
[email protected]
及更高版本。
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" : "." ,
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.
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
.env
file (eg REACT_APP_API_URL=http://api-staging.example.com
)$ npm install env-cmd --save
$ # or
$ yarn add env-cmd
package.json
, building with your new environment: {
"scripts" : {
"build:staging" : " env-cmd .env.staging npm run build "
}
}
Now you can run npm run build:staging
to build with the staging environment config. You can specify other environments in the same way.
Variables in .env.production
will be used as fallback because NODE_ENV
will always be set to production
for a build.
See this blog post on how to deploy your React app to Microsoft Azure.
See this blog post or this repo for a way to use automatic deployment to Azure App Service.
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.
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 just 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!
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"}]}
]
...
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
For more information see Add Firebase to your JavaScript Project.
注意:此功能可提供
[email protected]
及更高版本。
homepage
to package.json
The step below is important!
If you skip it, your app will not deploy correctly.
Open your package.json
and add a homepage
field for your project:
"homepage" : " https://myusername.github.io/my-app " ,
or for a GitHub user page:
"homepage" : " https://myusername.github.io " ,
or for a custom domain page:
"homepage" : " https://mywebsite.com " ,
Create React App uses the homepage
field to determine the root URL in the built HTML file.
gh-pages
and add deploy
to scripts
in package.json
Now, whenever you run npm run build
, you will see a cheat sheet with instructions on how to deploy to GitHub Pages.
To publish it at https://myusername.github.io/my-app, run:
npm install --save gh-pages
或者,您可以使用yarn
:
yarn add gh-pages
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",
The predeploy
script will run automatically before deploy
is run.
If you are deploying to a GitHub user page instead of a project page you'll need to make two additional modifications:
package.json
scripts to push deployments to master : "scripts": {
"predeploy": "npm run build",
- "deploy": "gh-pages -d build",
+ "deploy": "gh-pages -b master -d build",
npm run deploy
然後運行:
npm run deploy
gh-pages
Finally, make sure GitHub Pages option in your GitHub project settings is set to use the gh-pages
branch:
您可以通過將CNAME
文件添加到public/
文件夾中,以使用GitHub頁面配置自定義域。
Your CNAME file should look like this:
mywebsite.com
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:
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.index.html
page with a special redirect parameter. You would need to add a 404.html
file with the redirection code to the build
folder before deploying your project, and you'll need to add code handling the redirect parameter to index.html
. You can find a detailed explanation of this technique in this guide. If, when deploying, you get /dev/tty: No such a device or address
or a similar error, try the following:
git remote set-url origin https://<user>:<token>@github.com/<user>/<repo>
.npm run deploy
again 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
again Use the Heroku Buildpack for Create React App.
You can find instructions in Deploying React with Zero Configuration.
Sometimes npm run build
works locally but fails during deploy via Heroku. Following are the most common cases.
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
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.
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.
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"
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
.
To do a manual deploy to Netlify's CDN:
npm install netlify-cli -g
netlify deploy
Choose build
as the path to deploy.
To setup continuous delivery:
With this setup Netlify will build and deploy when you push to git or open a pull request:
Build your site
Support for client-side routing:
To support pushState
, make sure to create a public/_redirects
file with the following rewrite rules:
/* /index.html 200
When you build the project, Create React App will place the public
folder contents into the build output.
Now offers a zero-configuration single-command deployment. You can use now
to deploy your app for free.
Install the now
command-line tool either via the recommended desktop tool or via node with npm install -g now
.
Build your app by running npm run build
.
Move into the build directory by running cd build
.
Run now --name your-project-name
from within the build directory. You will see a now.sh URL in your output like this:
> Ready! https://your-project-name-tpspyhtdtk.now.sh (copied to clipboard)
Paste that URL into your browser when the build is complete, and you will see your deployed app.
Details are available in this article.
See this blog post on how to deploy your React app to Amazon Web Services S3 and CloudFront.
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.
When asked about the project path, make sure to specify the build
folder, for example:
project path: /path/to/project/build
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.
You can adjust various development and production settings by setting environment variables in your shell or with .env.
多變的 | 發展 | 生產 | 用法 |
---|---|---|---|
BROWSER | ✅ | By default, Create React App will open the default system browser, favoring Chrome on macOS. Specify a browser to override this behavior, or set it to none to disable it completely. If you need to customize the way the browser is launched, you can specify a node script instead. Any arguments passed to npm start will also be passed to this script, and the url where your app is served will be the last argument. Your script's file name must have the .js extension. | |
主持人 | ✅ | By default, the development web server binds to localhost . You may use this variable to specify a different host. | |
港口 | ✅ | By default, the development web server will attempt to listen on port 3000 or prompt you to attempt the next available port. You may use this variable to specify a different port. | |
https | ✅ | When set to true , Create React App will run the development server in https mode. | |
public_url | ✅ | Create React App assumes your application is hosted at the serving web server's root or a subpath as specified in package.json ( homepage ). Normally, Create React App ignores the hostname. You may use this variable to force assets to be referenced verbatim to the url you provide (hostname included). This may be particularly useful when using a CDN to host your application. | |
CI | ? | ✅ | When set to true , Create React App treats warnings as failures in the build. It also makes the test runner non-watching. Most CIs set this flag by default. |
REACT_EDITOR | ✅ | When an app crashes in development, you will see an error overlay with clickable stack trace. When you click on it, Create React App will try to determine the editor you are using based on currently running processes, and open the relevant source file. You can send a pull request to detect your editor of choice. Setting this environment variable overrides the automatic detection. If you do it, make sure your systems PATH environment variable points to your editor's bin folder. You can also set it to none to disable it completely. | |
CHOKIDAR_USEPOLLING | ✅ | When set to true , the watcher runs in polling mode, as necessary inside a VM. Use this option if npm start isn't detecting changes. | |
GENERATE_SOURCEMAP | ✅ | When set to false , source maps are not generated for a production build. This solves OOM issues on some smaller machines. | |
NODE_PATH | ✅ | ✅ | Same as NODE_PATH in Node.js, but only relative folders are allowed. Can be handy for emulating a monorepo setup by setting NODE_PATH=src . |
npm start
未檢測到更改When you save a file while npm start
is running, the browser should refresh with the updated code.
If this doesn't happen, try one of the following workarounds:
index.js
and you're referencing it by the folder name, you need to restart the watcher due to a Webpack bug..env
file in your project directory if it doesn't exist, and add CHOKIDAR_USEPOLLING=true
to it. This ensures that the next time you run npm start
, the watcher uses the polling mode, as necessary inside a VM.If none of these solutions help please leave a comment in this thread.
npm test
在Macos Sierra上懸掛或撞車If you run npm test
and the console gets stuck after printing react-scripts test
to the console there might be a problem with your Watchman installation as described in facebook/create-react-app#713.
We recommend deleting node_modules
in your project and running npm install
(or yarn
if you use it) first. If it doesn't help, you can try one of the numerous workarounds mentioned in these issues:
It is reported that installing Watchman 4.7.0 or newer fixes the issue. If you use Homebrew, you can run these commands to update it:
watchman shutdown-server
brew update
brew reinstall watchman
You can find other installation methods on the Watchman documentation page.
If this still doesn't help, try running launchctl unload -F ~/Library/LaunchAgents/com.github.facebook.watchman.plist
.
There are also reports that uninstalling Watchman fixes the issue. So if nothing else helps, remove it from your system and try again.
npm run build
出口太早It is reported that npm run build
can fail on machines with limited memory and no swap space, which is common in cloud environments. Even with small projects this command can increase RAM usage in your system by hundreds of megabytes, so if you have less than 1 GB of available memory your build is likely to fail with the following message:
The build failed because the process exited too early. This probably means the system ran out of memory or someone called
kill -9
on the process.
If you are completely sure that you didn't terminate the process, consider adding some swap space to the machine you're building on, or build the project locally.
npm run build
在Heroku上失敗This may be a problem with case sensitive filenames. Please refer to this section.
If you use a Moment.js, you might notice that only the English locale is available by default. This is because the locale files are large, and you probably only need a subset of all the locales provided by Moment.js.
To add a specific Moment.js locale to your bundle, you need to import it explicitly.
例如:
import moment from 'moment' ;
import 'moment/locale/fr' ;
If you are importing multiple locales this way, you can later switch between them by calling moment.locale()
with the locale name:
import moment from 'moment' ;
import 'moment/locale/fr' ;
import 'moment/locale/es' ;
// ...
moment . locale ( 'fr' ) ;
This will only work for locales that have been explicitly imported before.
npm run build
無法縮小Before [email protected]
, this problem was caused by third party node_modules
using modern JavaScript features because the minifier couldn't handle them during the build. This has been solved by compiling standard modern JavaScript features inside node_modules
in [email protected]
and higher.
If you're seeing this error, you're likely using an old version of react-scripts
. You can either fix it by avoiding a dependency that uses modern syntax, or by upgrading to react-scripts@>=2.0.0
and following the migration instructions in the changelog.
Ejecting lets you customize anything, but from that point on you have to maintain the configuration and scripts yourself. This can be daunting if you have many similar projects. In such cases instead of ejecting we recommend to fork react-scripts
and any other packages you need. This article dives into how to do it in depth. You can find more discussion in this issue.
If you have ideas for more “How To” recipes that should be on this page, let us know or contribute some!