使用npm-scripts发布Github Pages
使用npm-scripts发布Github Pages
将项目打包后部署到GitHub Pages 上是常见需求。
这里总结下通过npm-srcrips将项目发布到gh-pages分支。需要使用到gh-pages的库。
需要用到的环境
- node
- npm 或者yarn
- 本地项目,需要通过
create-react-app创建的React或者vue-cli创建的Vue项目 - gh-pages
- Github账户
过程
1. 在 GitHub 上创建与本地项目同名的远程仓库
2. 创建本地项目
React: create-react-app
$ 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.0
$ yarn global add @vue/cli $ vue create my-app
$ yarn global add @vue/cli-init $ vue init webpack my-app
然后运行项目:
$ 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中添加
"scripts": {
"pregh": "npm run build",
"gh": "gh-pages -d dist"
}React:
在package.json中添加
"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 打造超溜的前端工作流(需付费)
5.修改publickPath
此时,虽然可以发布,但所有相关的静态文件的目录都是指向https://<username>.github.io的,而实际的静态文件的位置是在https://<username>.github.io/<repo-name>中。
Vue:
在npm build之前,修改config/index.js的配置:
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 项目