Usage with Next.js SSR
See original GitHub issueFirst of all: Thanks so much for creating this great library. I’ve spend too many hours trying to configured Monaco to get VSC themes working before I found Shiki. 😅
I’m trying to use Shiki in a Next.js app using Next.js’ SSR feature via getStaticProps
. Everything works great during local development (via next dev
) however the app breaks in production after running next build
(which bundled the app) resulting in errors like these:
The reason for this is that Shiki dynamically tries to access the theme/grammar files using the fs
Node package. However these resources are no longer available after the next build
step. Next.js uses nft to automatically detect and bundle assets. It would be great if Shiki could access the required assets in a way that nft
can understand it and it therefore works with Next.js.
As a temporary workaround I’m doing the following:
const theme = require('shiki/themes/github-light.json')
const grammar = require('shiki/languages/tsx.tmLanguage.json')
const highlighter = await getHighlighter({
theme,
langs: [{ id: 'tsx', scopeName: 'source.tsx', grammar }],
})
Issue Analytics
- State:
- Created 3 years ago
- Comments:10
Top GitHub Comments
@octref the
next-shiki
repo will always work, because the Shiki highlighting is done atgetStaticProps
, which is run at build-time, which has the fullnode_modules
there.However, I think it’s not what @schickling and others are asking for in this issue. They are asking for SSR, which is run-time, and on server-side.
(basically in next-js there are 3 states:
That being said, I think I successfully have Shiki on getServerSideProps! This means:
The trick is:
The key here is to let Vercel nft to know about the existence of Shiki/themes and shiki/languages so they are included in the production run-time
Sample code: https://github.com/thien-do/memos.pub/blob/a3babb1f149f05c43012278331f885d81f5fcfac/lib/mdx/plugins/code.ts
@THiragi The currently recommended way to include language/theme JSON files are not bundling them, but serving them as static assets.