🪗 Kotlin jvm 实现静态博客生成器随记
2023-12-28
零、用kotlin写博客生成器
-
Kotlin-jvm:前端生成器 -
Notion:数据库 -
Typescript:编译成 JavaScript
一、开发环境配置
- kotlinx.html
: A kotlinx.html library provides DSL to build HTML to Writer/ Appendableor DOM. - notion-sdk-jvm
: A Notion APISDK for any JVM language users. - mordant
: Colorful styling for command-line applications.
dependencies {
testImplementation(kotlin("test"))
val kotlinxHtmlVersion = "0.9.1"
val notionSdkVersion = "1.9.0"
val mordantVersion = "2.1.0"
implementation("org.jetbrains.kotlinx:kotlinx-html-jvm:${kotlinxHtmlVersion}")
implementation("com.github.seratch:notion-sdk-jvm-core:${notionSdkVersion}")
implementation("com.github.ajalt.mordant:mordant:${mordantVersion}")
}
二、从 Notion 数据库抓取数据
val notionToken = System.getenv("NOTION_TOKEN");
NotionClient(token = notionToken).use { client ->
//todo
}
三、数据的保存与动态更新
数据的序列化和反序列化

数据的保存结构
notionData
- database.json
- queryDatabaseResult.json
- a.json //某个文章的id
-> a //某个文章的id的文件夹,递归地存储block内容
- b.json
- img_b.png //如果某个block是图片,则存储图片资源以img_id的格式

动态更新数据
private fun isBlockNeedToUpdate(block: Block, parentPath: Path): Boolean {
val pageFile = parentPath.childPath(block.id!! + ".json").toFile()
if (pageFile.exists() && pageFile.isFile) {
val existPage = client.jsonSerializer.toBlock(pageFile.readText())
if (existPage.lastEditedTime == block.lastEditedTime)
return false
}
return true
}
四、用 Kotlin 生成 Html
写入 html
filewriter.appendHTML().html {
head{
//...
}
body{
//...
}
}
filewriter.close()
五、CSS (SCSS)和 js(Typescript 编译)
SCSS → CSS
SCSS 是 Sass 兼容 css 的版本,其后缀名为 .scss,SCSS 较 CSS 拥有更丰富的语言特性,同时向下兼容 CSS. 我的项目最开始用原生 CSS 书写,为了方便迁移和使用 IDE 的自动格式化,我选择了 SCSS
安装 Sass
如果你不了解 npm,请见 https://www.npmjs.com/
npm install -g sass
编译 SCSS
sass --watch <input> <output>
TypeScript → JavaScript
安装 TypeScript
npm install -g typescript --save-dev
编译 TypeScript
find ./src/main/typescript/ -name "*.ts" -type f >ts-files.txt
tsc @ts-files.txt --outDIr ./static/assets/js --removeComments
rm ts-files.txt

六、本地服务器调试
结语