自訂範本
注意:此功能需要
react-scripts@3.3.0
及以上版本。
自訂範本讓您能選擇一個範本来建立專案,同時保留建立 React 應用程式的所有功能。
您會注意到自訂範本的命名格式永遠都是 cra-template-[範本名稱]
,不過您只需要在建立指令中提供 [範本名稱]
即可。
範圍範本也受支援,命名格式為 @[範圍名稱]/cra-template
或 @[範圍名稱]/cra-template-[範本名稱]
,而且可分別透過 @[範圍]
和 @[範圍]/[範本名稱]
安裝。
npx create-react-app my-app --template [template-name]
尋找自訂範本
我們預設提供兩個範本
不過,您可以在 npm 上搜尋 "cra-template-*",找到許多由社群提供的絕佳範本。
建立範本
如果您有興趣建立自訂範本,請先了解一下我們建立 cra-template
的方式。
模板必須有以下結構
cra-template-[template-name]/
README.md (for npm)
template.json
package.json
template/
README.md (for projects created from this template)
gitignore
public/
index.html
src/
index.js (or index.tsx)
測試模板
若要測試本地端模板,請使用 file:
前綴將檔案路徑傳遞至範本來源的目錄。
npx create-react-app my-app --template file:../path/to/your/template/cra-template-[template-name]
template
資料夾
當 Create React App 安裝時,此資料夾會複製到使用者的應用程式目錄。在此過程中,檔案 gitignore
會重新命名為 .gitignore
。
您可以在這裡新增任何想要的檔案,但至少必須具備上述指定的檔案。
template.json
檔案
這是您模板的組態檔案。由於這項功能是新增的,後續會新增更多選項。目前僅支援 package
金鑰。
package
金鑰讓您能夠提供任何您想要新增到新專案的 package.json
的金鑰/值,例如套件相依關係和任何模板依賴的客製化腳本。
以下是 template.json
範例檔
{
"package": {
"dependencies": {
"eslint-plugin-jsx-a11y": "^6.2.3",
"serve": "^11.2.0"
},
"scripts": {
"serve": "serve -s build",
"build-and-serve": "npm run build && npm run serve"
},
"eslintConfig": {
"extends": ["react-app", "plugin:jsx-a11y/recommended"],
"plugins": ["jsx-a11y"]
}
}
}
您為 "dependencies"
和 "scripts"
新增的任何值都將與 Create React App 預設值合併。任何其他金鑰的值都將直接使用,取代任何匹配的 Create React App 預設值。
為了方便,我們會在自訂 "scripts"
中,以及在使用紗線初始化專案時的 README
中,始終將 npm run
取代為 yarn
。