javascript - 是否可以不重建整个应用程序而仅在 Nextjs 中生成新的静态文件?
问题描述
我刚开始使用NextJs getStaticProps
,生成的静态文件build time
很整洁。但是我的内容不会保持不变,我需要更新静态文件,但每次修改时重新构建应用程序的成本很高。有没有办法只生成新的静态文件。getServerSideProps
原来在第一个字节之前花费了大量时间。
解决方案
根据您的内容类型,增量静态再生可能是一个很好的解决方案。但根据我的经验,它在呈现目录/类别页面时引入了其他问题。由于 nextjs 不知道您的数据的一部分是否依赖于其他数据,因此它可能会呈现一个旧的目录页面,其中包含指向不再存在的帖子或产品的链接。这通常与动态路由的“后备”功能结合使用。
它也不会在您进行更改后立即刷新您的页面,因此您只会在一段时间后看到结果。
可能的解决方法是通过 ajax 在类别页面上动态加载帖子/产品。您将失去一部分 UX 和 SEO,但另一方面,此解决方案相对易于维护。
通过直接访问自定义服务器中的缓存,还有一个选项或更确切地说是破解来重建部分保存的内容。将 'purge=1' 添加到要刷新的页面地址。
const { ServerResponse, createServer } = require('http')
const next = require('next')
const { promises } = require('fs')
const path = require('path')
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
const purgeByPath = async url => {
const pathname = url == '/' ? '/index' : url
const fullPathname = `.next/server/pages${pathname}`
const fullPathHTML = `${fullPathname}.html`
const fullPathJSON = `${fullPathname}.json`
try {
await promises.unlink(fullPathHTML)
await promises.unlink(fullPathJSON)
} catch (err) {
console.log(`Could not unlink cache files: ${err}`)
}
await app.incrementalCache.cache.del(pathname)
let req = new Request(process.env.BASE_HOST + url)
let res = new ServerResponse(req)
await app.renderToHTML(req, res, url, { _nextDataReq: true })
}
app.prepare().then(() => {
createServer(async (req, res) => {
const url = new URL(req.url, "http://localhost:3000/")
if (req.method == 'POST' && req.url == '/purge-cache') {
let raw = ''
req.on('data', chunk => raw += chunk)
req.on('end', async () => {
const data = JSON.parse(raw)
if (!data || !data.urls) {
res.statusCode = 400
res.end()
return
}
for (let url of data.urls) {
console.log(`Cleaning cache on: ${url}`)
await purgeByPath(url)
}
res.end()
})
} else if (url.searchParams.get('purge') == '1') {
await purgeByPath(req.url)
res.end()
} else {
handle(req, res)
}
}).listen(3000, (err) => {
if (err) throw err
console.log(`> Ready on http://localhost:3000/`)
})
})
静态缓存由两部分组成:
- 位于
.next/server/pages
每个路由的静态缓存文件可能有两个文件 html 和 json。很可能您需要删除两者。 - 内存缓存。一旦您的应用程序缓存了页面并将其保存到内存中,它就不会转到硬盘驱动器上的文件,而是会从内存中加载内容。所以你也需要删除它。
缓存实现未记录在案,可能在未来版本中被交换或删除。
这不适用于 vercel,并且在缩放方面存在一些问题。您还应该添加某种安全令牌来清除路由。
推荐阅读
- sql-server - ADO.NET 中的数据类型映射
- bash - `base64 --decode` 不会像 `echo` 那样用值替换变量
- javascript - 如何在快递中使用这个?
- python - 简单的条件运算符 python
- docker - Docker 映像 .Net 框架应用程序
- spring-boot - Spring MongoDB 无法实例化 Map 类型:org.springframework.messaging.MessageHeaders
- sql-server - SQL Server 将数据从一个表复制/复制到另一个表
- python - 获取 Pandas 中两行之间的差异
- android-studio - adb.exe 启动服务器失败--必要时手动运行
- c++ - 用于实时信号处理的快速 C++ 正弦和余弦替代方案