当前位置:网站首页>Next. JS + cloud development webify creates an excellent website
Next. JS + cloud development webify creates an excellent website
2022-06-24 04:11:00 【Tencent cloud development TCB】
Next.js Where's cool ?
Before using Next.js + strapi I made a simple blog site and wrote an article by the way Next.js A concise tutorial , after Next Itself has been developing rapidly . Take advantage of js In terms of ability, I did :
- Excellent development experience
- Excellent website, best ” dynamic “,“ static ” Balance
In terms of characteristics , Support :
- SSR(Server Side Rendering) Provide getServerSideProps Method , Request data when the user accesses , Suitable for real-time data pages .
- SSG(Static Site Generation) Provide getStaticProps,getStaticPaths Method to pre produce static pages ;
And the cool thing is : Use fallback,revalidate To support certain dynamics .
This energy “ dynamic ” Of SSG Nature is what I need , Keep static access , And when I add and modify articles , The site can be updated automatically . Excellent !!
Why do you need to come Webify“ Toss about ” Once ?
Now that it's cool , Why is there today's article , Why do you need to toss around ?
The reason is also simple : The cost is a little higher , For good access speed , You need a virtual machine with good performance , A certain bandwidth . For general personal blogs , The investment is not cost-effective .
Here is a grand invitation to our solution : Tencent cloud development Webify, In short, it's similar to vercel Of Serverless hosted services , But support more frameworks , And it's a domestic service provider , Cheap and first-class access .
There are pictures to prove :
And now hosting , You can get it for free 300 Yuan no threshold voucher , Sweet ~ If you are interested, you can click the link below to learn about :https://cloud.tencent.com/developer/article/1871549
CloudBase Webify actual combat
For general articles, use similar github Management is simple ,Webify Supported version Github、Gitlab、Gitee Service provider , It is said that he will support Coding:
- Vue.js (vue-cli)
- React.js (create-react-app)
- Hexo
- Gatsby.js
- Angular
- Next.js SSG
- Nuxt.js SSG
- And auto adaptation framework
Take this blog next For example ,Webify It's actually used next export The ability of , After construction , Deploy static files directly to server.
If your blog post , Use it directly md,git management , See here OK 了 ,git Submit ,Webify Automatically redeploy your site .cool~~
The problem is if your site data comes from something like strapi such serverless cms What do I do ?next export I won't support it next SSG in “ dynamic ” Characteristics of (fallback,revalidate).
Webify Higher order —— automation Webify
In fact, the method is also very simple , Add a bridging service , Let your serverless cms The update changes to git Just fine .
To be specific strapi As an example :
- strapi Data Publishing
- web hook To a custom Bridging Service .
- Bridge service update site git.
- Weify Trigger redeployment .
Of course, if you follow up webify Support more redeployment modes , It will be simpler here .
At first glance , It seems to be back to the origin , We still need a server , Here is another guest of this article ,tcb Cloud functions . The above on-demand service , Using cloud functions is the most appropriate , You don't need a virtual machine that's always on , You only need to evoke the cloud function when updating the article , Stop with use , The cost is low .
According to the scenario of this blog , We let the bridge service run , Automatically generate the site's sitemap To github Give me one hand and get two .
- be used for sitemap Generate site map xml;
- Use @octokit/rest,@octokit/plugin-create-or-update-text-file To update github In the file .
Here's the simplified code :
Generate site map sitemap.xml
const {
SitemapStream,
streamToPromise
} = require('sitemap')
const {
Readable,
Transform,
pipeline
} = require('stream')
const {
apiRequest,
getPostsWithGraphql
} = require('./request')
const PaginationLimit = 30
module.exports = ({
hostname,
cmsUrl
}) => {
async function getPostSitemap() {
const smStream = new SitemapStream({
hostname,
});
let page = 0;
const postStream = new Readable({
objectMode: true,
async read(size) {
const result = await getPostsWithGraphql(`${cmsUrl}/graphql`, page++, PaginationLimit);
if (result.error || !Array.isArray(result.data.posts)) {
this.push(null);
} else {
result.data.posts.forEach((item) => {
this.push(item);
});
if (result.data.posts.length < PaginationLimit) {
this.push(null);
}
}
},
});
const trans = new Transform({
objectMode: true,
transform(data, encoding, callback) {
callback(null, {
url: `/p/${data.book.slug || data.book.uuid}/${
data.slug || data.uuid
}`,
changefreq: 'daily',
priority: 1,
lastmod: new Date(data.updated_at),
});
},
});
const buffer = await streamToPromise(pipeline(postStream, trans, smStream, (e) => {
// throw e;
}))
return {
path: 'public/sitemap.xml',
content: buffer.toString()
}
}
return Promise.all([
// getHomeSitemap(),
// getBookSitemap(),
getPostSitemap()
])
}to update Github In the file
'use strict';
const {
Octokit
} = require("@octokit/rest");
const {
createOrUpdateTextFile,
} = require("@octokit/plugin-create-or-update-text-file");
const {
throttling
} = require("@octokit/plugin-throttling");
const getSitemaps = require('./sitemap')
const MyOctokit = Octokit.plugin(createOrUpdateTextFile, throttling);
exports.main = async (event, context) => {
const {
headers: {
authorization,
'x-strapi-event': strapiEvent
},
body
} = event;
const {
model,
entry
} = JSON.parse(body)
const {
CMS_TOKEN,
GITHUB_ACCESS_TOKEN,
BLOG_URL = 'https://hicc.pro',
CMS_URL = 'https://cms.hicc.pro'
} = process.env;
// strapi Add an encryption key to ensure security
if (CMS_TOKEN !== authorization) {
return {
doTrigger: false
}
}
let doTrigger = false // TODO: Identify the real release
const siteMaps = await getSitemaps({
hostname: BLOG_URL,
cmsUrl: CMS_URL
})
const octokit = new MyOctokit({
auth: GITHUB_ACCESS_TOKEN,
throttle: {
onRateLimit: (retryAfter, options) => {
console.warn(
`Request quota exhausted for request ${options.method} ${options.url}`
);
// Retry twice after hitting a rate limit error, then give up
if (options.request.retryCount <= 2) {
console.log(`Retrying after ${retryAfter} seconds!`);
return true;
}
},
onAbuseLimit: (retryAfter, options) => {
// does not retry, only logs a warning
console.warn(
`Abuse detected for request ${options.method} ${options.url}`
);
},
},
});
await Promise.all(siteMaps.map(({
path,
content
}) => {
return octokit.createOrUpdateTextFile({
// replace the owner and email with your own details
owner: "xxx",
repo: "xxx",
path,
message: `feat: update ${path} programatically`,
content: content,
branch: 'master',
sha: '',
committer: {
name: "xxx",
email: "[email protected]",
},
author: {
name: "xxx",
email: "[email protected]",
},
})
}))
return {
doTrigger
}
};author :hicc, Senior front end development engineer of Tencent .
Welcome to visit Webify Official website :https://webify.cloudbase.net/
Personal site support plan , Get... Free of charge 300 Yuan no threshold voucher :https://webify.cloudbase.net/blog/personal-site-plan
边栏推荐
- Backup method of mysqldump
- Pycharm from installation to full armament
- Use the fluxbox desktop as your window manager
- openGauss 3.0版本源码编译安装指南
- 华为云GaussDB(for Redis)揭秘第19期:GaussDB(for Redis)全面对比Codis
- Go operation mongodb
- Opengauss version 3.0 source code compilation and installation guide
- How EDI changes supply chain management
- Received status code 502 from server: Bad Gateway
- Kubernetes resource topology aware scheduling optimization
猜你喜欢

Black hat actual combat SEO: never be found hijacking

抢先报名丨新一代 HTAP 数据库如何在云上重塑?TiDB V6 线上发布会即将揭晓!

英特尔 XTU 官方超频工具已支持 Win11 22H2 和 13 代酷睿 Raptor Lake 处理器

Flutter series: offstage in flutter
![[numpy] numpy's judgment on Nan value](/img/aa/dc75a86bbb9f5a235b1baf5f3495ff.png)
[numpy] numpy's judgment on Nan value

Idea 1 of SQL injection bypassing the security dog

Clang代码覆盖率检测(插桩技术)

Application practice | Apache Doris integrates iceberg + Flink CDC to build a real-time federated query and analysis architecture integrating lake and warehouse

Yuanqi forest pushes "youkuang", and farmers' mountain springs follow the "roll"?

Kubernetes 资源拓扑感知调度优化
随机推荐
[new light weight first purchase special] 1-core 2g5m light weight application server costs 50 yuan in the first year. It is cost-effective and helps you get on the cloud easily!
Why is on-line monitoring of equipment more and more valued by people?
我与物联有个约定
Unable to access the CVM self built container outside the TKE cluster pod
TCP three handshakes and four waves
API real-time signature scheme based on Yapi
How can the new generation of HTAP databases be reshaped in the cloud? Tidb V6 online conference will be announced soon!
Browser rendering mechanism
Web technology sharing | [map] to realize customized track playback
[numpy] numpy's judgment on Nan value
开源一款监控数据采集器,啥都能监控
[hot promotion] Tencent cloud enterprise cloud disk solution
Maintain the visibility of data automation: logging, auditing and error handling of the bridge of knowledge and action
应用实践 | Apache Doris 整合 Iceberg + Flink CDC 构建实时湖仓一体的联邦查询分析架构
祝贺钟君成为 CHAOSS Metric Model 工作组的 Maintainer
Clickhouse (02) Clickhouse architecture design introduction overview and Clickhouse data slicing design
How to gracefully handle and return errors in go (1) -- error handling inside functions
Easygbs video playback protocol only webrtc can play. Troubleshooting
LeetCode 938. Range sum of binary search tree
"." in the structure of C language And "- & gt;" Differences between