将项目打包后部署到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 项目