Github is a repository that allows users to access and store data on their blogs. Github is a repository that allows users to access data on their blogs. Github is a repository that allows users to access data on their blogs.
Blog address
🚗 Why Umi
For those of you who have used React, you probably know the Umi framework. If you haven’t, I also recommend that you check out the Portal.
Umi built-in react, Preact, Webpack, React – Router, Babel, etc., can be done out of the box, its unique contract route can save us the steps of route configuration. So the use of Umi scaffolding new project, directory structure is very clear. Here is the directory structure for the next project created by Umi:
.├ ─ dist/ // Default Build ├─ mock/ // Base on Express ├─ config/ ├─ config.js with.umirc.js, └─ └─ SRC // / └─ ├─ layouts/index.js // ├─ pages/ // / setup // ├─. .gitignore ├─.umi-production/ // build temporary directory ├─ document.ejs // HTML Template ├─ 404.js // 404 page ├─ page1. Js // umitestWill match all. Test. Js and the e2e. The file at the end of js └ ─ ─ page2. Js / / page 2, arbitrary naming ├ ─ ─ global. The CSS / / global style file of the agreement, automatic introduction, You can also use global.less ├─ global.js // Here you can add Polyfill ├─ app.js // Runtime Config file ├─.umirc.js // umi config, same as config/config.js, ├─ ├─ ├─ ├─ package.jsonCopy the code
🚢 markdown
Github Issues supports MarkDown format, so the presentation of our blog posts must support Markdown format. Here I choose React-Markdown.
The use of the react – markdown
First you need to install:
npm i react-markdown
Copy the code
React-markdown does not support code syntax highlighting by default, so you need to install the react-syntax-highlighter library:
npm i react-syntax-highlighter
Copy the code
Since our blog is based on Github Markdown, there are some differences between the react-Markdown style and the react-Markdown style. I also introduced Github Markdown CSS to solve the style rendering problem.
For ease of use, a Markdown component is encapsulated:
// index.js
import ReactMarkdown from 'react-markdown';
import CodeBlock from '@/components/markdown/codeBlock';
import 'github-markdown-css';
import './index.less';
export default (props) => {
const { dataSource } = props;
return (
<ReactMarkdown
escapeHtml={false}
renderers={{
code: CodeBlock,}}className="markdown-body"
source={dataSource}
/>)}Copy the code
Code highlighting:
// codeBlock.js
import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import { PrismLight as SyntaxHighlighter } from "react-syntax-highlighter";
// Set the highlighting style
import { solarizedlight } from "react-syntax-highlighter/dist/esm/styles/prism";
// Set the highlighted language
import { jsx, javascript, sass, scss, less, css } from "react-syntax-highlighter/dist/esm/languages/prism";
class CodeBlock extends PureComponent {
static propTypes = {
value: PropTypes.string.isRequired,
language: PropTypes.string
};
static defaultProps = {
language: null
};
componentDidMount() {
// Register syntax to be highlighted,
// Note: this does not work if it is not set to be packaged for use by third parties
SyntaxHighlighter.registerLanguage("jsx", jsx);
SyntaxHighlighter.registerLanguage("javascript", javascript);
SyntaxHighlighter.registerLanguage("sass", sass);
SyntaxHighlighter.registerLanguage("scss", scss);
SyntaxHighlighter.registerLanguage("less", less);
SyntaxHighlighter.registerLanguage("css", css);
}
render() {
const { language, value } = this.props;
return (
<figure className="highlight">
<SyntaxHighlighter language={language} style={solarizedlight}>
{value}
</SyntaxHighlighter>
</figure>); }}export default CodeBlock;
Copy the code
One thing to note about code highlighting is that we have to use the registerLanguage method to register the language you want to highlight, and react-syntax-highlighter provides several code highlighting styles for us to use. In the react – syntax highlighter/dist/esm/styles/prism directory can choose code highlighting the style you like, here I chose solarizedlight this kind of style.
🦁️ About route mode selection
React routes are routed in three ways: The history route, hash route, and memory route are commonly used. Our blog will eventually be published and deployed to The Github page. If you choose the History route, you will get a 404 error if you refresh the page in a non-root path after deployment.
Single-page applications typically require a server to redirect all pages to index.html. For example, if we refresh the HTTP :xxx.com/list page, the server will look for resource files in the list directory at the root, which obviously do not exist on the file server, and will return 404.
When faced with this problem, we usually choose to do the following configuration on nginx:
location /{
root /data/nginx/html;
index index.html index.htm;
error_page 404 /index.html;
}
Copy the code
This means that if a resource cannot be found, it is automatically redirected to index.html.
Obviously, we can’t do that on Github page, so we’re just going to be lazy and choose a hash route.
Umirc. Js file in the root directory can be directly configured as follows:
export default {
history: 'hash',}Copy the code
🌻 about front-end cross-domain issues
We said to the front, when we are in authority certification, according to the authorization code to https://github.com/login/oauth/access_token to request this address, when acquiring the Token, will cross domain problems. So what’s a good way to solve this problem?
I will not elaborate on the cause of cross-domain. If you are not clear, you can go to Google. Here, in order to solve the cross-domain problem, I adopted the METHOD of CORS, which is to add the header returned by the request and the request header that allows cross-domain operation.
If the github server receives a request for authentication from a third-party proxy interface, the third-party proxy interface sends the actual request to the Github server. This third-party proxy interface allows cross-domain headers.
About the zeito. Co
So now the problem is very simple, to provide a third-party authentication proxy interface can solve our problem, in order to practice the title of the article “free” two words, to rent a server for this interface to provide authentication interface is obviously not worth the loss, here I recommend the website zeit.co, He allowed us to deploy a static website or Serverless Functions for free. The official website says:
ZEIT Now is a cloud platform for static sites and Serverless Functions. It enables developers to host websites and web services that deploy instantly, scale automatically, and requires no supervision, all with no configuration.
Here we use the Serverless Functions provided by Zeit. Co to achieve a third-party proxy interface.
Zeit. co offers two ways to deploy its services.
- The first way is to deploy using the Now Cli tool:
- You need to install the Now CLI tool first.
npm i -g now
Copy the code
- And then go to Now
now login
Copy the code
- Create your own projects You can create your own projects using templates based on your needs, or just use existing projects.
npm init next-app my-next-project
Copy the code
4. Publish your own project to Zeit.co
now
Copy the code
This method is simple and easy to use, but there is a drawback, the second step may be subject to network problems, can not log in, of course, if you have a ladder, this is not a problem. If you don’t have a ladder, it doesn’t matter. Here’s a second way to deploy your application.
- GitHub is also a convenient way to deploy your application, and I recommend it for the following advantages:
- Deploys every push in branches and pull requests to preview changes live
- Updates production domains with the most recent changes from the master branch
- Instant rollbacks for production domains when reverting changes
Every time you submit code to Github, the automatic deployment function will be triggered and the domain name will be updated automatically.
I use the second approach to deploy my application. The following describes the specific process.
First you need to register an account on Zeito. co and associate it with your Github account. Then you can go to the Dashboard page, where you can create your own application and select an existing project From Github to create it.
Create a Serverless Functions
Create a date.js file in the API directory of the root directory, for example:
// date.js
module.exports = (req, res) = > {
const date = new Date().toString();
res.status(200).send(date);
};
Copy the code
When we access/API /date, the interface returns the current system time, that is, we do not need to specify routing files, each file is an independent route, similar to umi contract route.
Having covered the Serverless Functions above, we now return to our requirement to create a third-party proxy interface that handles the Github authorization interface.
Create a githubauth.js file in the API directory:
// githubAuth.js
require('es6-promise').polyfill();
require('isomorphic-fetch');
module.exports = async (req, res) => {
// Set the request header to allow cross-domain
res.setHeader("Access-Control-Allow-Origin"."*");
const { query: { code } } = req;
const clientID = 'your clientID';
const clientSecret = 'your clientSecret';
const url = 'https://github.com/login/oauth/access_token?' +
`client_id=${clientID}& ` +
`client_secret=${clientSecret}& ` +
`code=${code}`;
try{
await fetch(url, {
method: 'POST'.headers: {
'Accept': 'application/json'.'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
}
}).then(response= > {
if(response.status === 200) {
return response.json();
}
}).then(data= >{ res.json({ data }); })}};Copy the code
Res.setheader (” access-Control-allow-origin “, “*”) is our cross-domain Header. You can refer to the complete code here.
🌹 Deploy your blog
After the front-end code is written, it is necessary to consider the problem of deployment. Here I choose to deploy to Github Pages. The reason for choosing Github Pages is simple:
- Automatic code integration: Github Pages are integrated into Github and can be automatically redeployed as code updates are submitted, making it very easy to use.
- Free domain name: Free github. IO domain name, free to deploy your static site, and can configure your own domain name according to your needs.
- Unlimited number: There is no limit to how many Github Pages can use, and each Github Repository can be deployed as a static site.
The specific usage and configuration methods are not described here, you can Google, or refer to here.
The following is the qr code picture of my official account, welcome to follow.