Ktor和vite的丝滑搭配

目前为止Java服务端渲染开发最舒服的一个搭配

作者: lookroot

日期: 2025/06/16

前言

我一直都喜欢用服务端渲染的方式,但是Java的服务端渲染不如php的框架对现代化的前端框架支持好,比如我想要使用tailwindcss偷偷懒都不太方便。

之前也探索过类似的方案Springboot服务端渲染中vite,webpack的妙用,都不是特别丝滑,始终热重载都没有php和node的舒服。

本文这套ktor + vite的体验实测就非常舒服了。

整体思路

ktor配置开发模式支持热重载,并在本地启动的时候把资源路径映射成绝对路径而不是编译后的文件,这样前端编译的资源就不用再需要jvm编译了。

vite配置把指定页面和资源打包到ktor配置的绝对路径即可。

ktor项目

初始化项目

 implementation("io.ktor:ktor-server-thymeleaf")

项目配置

ktor:
# 打开开发模式
  development: true
  deployment:
    port: 8080

插件配置

# 安装thymeleaf插件,并支持开发模式直接请求指定文件 这样就不需要编译  
install(Thymeleaf) {
        setTemplateResolver((if (isDev) {
            FileTemplateResolver().apply {
                cacheManager = null
                prefix = "server/src/main/resources/static/"
            }
        } else {
            ClassLoaderTemplateResolver().apply {
                prefix = "static/"
            }
        }).apply {
            suffix = ".html"
            characterEncoding = "utf-8"
        })
    }
# 路由下资源文件 开发环境写死
   routing {
        if (developmentMode) {
            staticFiles("/", File("server/src/main/resources/static/"))
        } else {
            staticResources("/", "/web")
            staticResources("/", "/static")
        }
    }

vite项目

{
  "name": "thymeleaf",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "start": "tsc && vite build --watch"
  },
  "devDependencies": {
    "typescript": "~5.7.2",
    "vite": "^6.1.0"
  },
  "dependencies": {
    "@tailwindcss/vite": "^4.0.7",
    "animate.css": "^4.1.1",
    "tailwindcss": "^4.0.7"
  }
}

vite配置

import { defineConfig } from 'vite'
import tailwindcss from '@tailwindcss/vite'

export default defineConfig({
    base:'web',
    build: {
        emptyOutDir: true,
        outDir: "../server/src/main/resources/static/web",
        rollupOptions: {
            input: {
                main: 'index.html',
                channel: 'channel.html',
                common: 'common.html',
                doc: 'doc.html',
            },
            output:{
                entryFileNames: 'app.js',
                assetFileNames: '[name].[ext]',
                chunkFileNames: 'app.js',
            }
        }
    },
    server: {
        port: 3000,
        host: '0.0.0.0',
    },
    plugins: [
        tailwindcss(),
    ],
})

启动项目pnpm run start

这时候就发现资源已经被正确打包到指定路径了,修改样式保存,浏览器刷新可直接看到效果。

image-20250616132253808