將項目打包後部署到GitHub Pages 上是常見需求。
這裏總結下經過npm-srcrips將項目發佈到gh-pages分支。須要使用到gh-pages的庫。javascript
create-react-app
建立的React
或者vue-cli
建立的Vue
項目React: create-react-apphtml
$ yarn global add create-react-app $ create-react-app my-app
如果使用npm5.2+版本前端
$ npx create-react-app my-app $ cd my-app $ yarn start
Vue: vue-cli
@vue/cli 3.0vue
$ yarn global add @vue/cli $ vue create my-app
vue-cli@2.xjava
$ yarn global add @vue/cli-init $ vue init webpack my-app
而後運行項目:node
$ cd my-app $ yarn install $ yarn start
$ git init $ git add . $ git commit -m 'create app' $ git remote add origin <git url> $ git push -u origin master
Vue:
在package.json中添加react
"scripts": { "pregh": "npm run build", "gh": "gh-pages -d dist" }
React:
在package.json中添加webpack
"scripts": { "pregh": "npm run build", "gh": "gh-pages -d dist" }
Vue在build
時生成的目錄是dist
,而React在build
時生成的目錄時build
。gh
是自定義的腳本名稱,你也能夠叫gh-deploy
等等。
想要在腳本執行以前還另外執行其餘命令,就在自定義腳本前添加預處理鉤子,形式是pre
加gh
腳本名稱。
關於npm-scripts的知識,參考:
npm scripts 使用指南
用 npm script 打造超溜的前端工做流(需付費)git
此時,雖然能夠發佈,但全部相關的靜態文件的目錄都是指向https://<username>.github.io
的,而實際的靜態文件的位置是在https://<username>.github.io/<repo-name>
中。
Vue:
在npm build
以前,修改config/index.js
的配置:github
module.exports = { ... build: { ... assetsPublicPath: '', // 此處原來是assetsPublicPath: '/' ... }
React:
與Vue不一樣,create-react-app
是將全部scripts文件隱藏的。想要將講臺文件指向正確的目錄,是經過在package.json
中添加homepage
選項。
{ "author": ..., "homepage": "https://<username>.github.io/<repo-name>", ... "scripts": { ... } }
$ npm run gh # or $ yarn run gh
查看遠程的gh-pages
分支,此時分支下應包含一個index.html
和其餘靜態文件(如static
目錄)。
以後就能夠經過https://<username>.github.io/<repo-name>
訪問應用程序了。
相關參考:
React的github pages 發佈,Deploying a React App* to GitHub Pages
如何在 GitHub Pages 上部署 vue-cli 項目