使用npm-scripts發佈Github Pages

使用npm-scripts發佈Github Pages

將項目打包後部署到GitHub Pages 上是常見需求。
這裏總結下經過npm-srcrips將項目發佈到gh-pages分支。須要使用到gh-pages的庫。javascript

須要用到的環境

  • node
  • npm 或者yarn
  • 本地項目,須要經過create-react-app建立的React或者vue-cli建立的Vue項目
  • gh-pages
  • Github帳戶

過程

1. 在 GitHub 上建立與本地項目同名的遠程倉庫

2. 建立本地項目

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

3.將本地項目 push 到遠程:

$ git init
$ git add .
$ git commit -m 'create app'
$ git remote add origin <git url>
$ git push -u origin master

4.添加npm-scripts:

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等等。
想要在腳本執行以前還另外執行其餘命令,就在自定義腳本前添加預處理鉤子,形式是pregh腳本名稱。
關於npm-scripts的知識,參考:
npm scripts 使用指南
用 npm script 打造超溜的前端工做流(需付費)git

5.修改publickPath

此時,雖然能夠發佈,但全部相關的靜態文件的目錄都是指向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": { ... }
}

6.生成生產版本,並部署到Github Page

$ 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 項目

相關文章
相關標籤/搜索