@ 表达式- 代码/ 核心
核心一揽子措施 表达式代码,用于在网络上显示源代码的引擎.
文档
读取表达式代码文件 了解更多关于表达码提供的特点.
我什么时候用这个?
直接使用此核心软件包 仅建议预先使用。 。 。 .
除非您是插件或集成作者, 您可能应该使用更高层次的软件包, 如 astro-expressive-code 或者说 rehype-expressive-code 而不是这个.
安装
npm install @expressive-code/core
用法实例
// File: generate-html-core.mjs
import { ExpressiveCodeEngine } from '@expressive-code/core'
import { toHtml } from '@expressive-code/core/hast'
import fs from 'fs'
const ec = new ExpressiveCodeEngine({
plugins: [
// Add your plugins here
],
})
// Get base styles that should be included on the page
// (they are independent of the rendered code blocks)
const baseStyles = await ec.getBaseStyles()
const themeStyles = await ec.getThemeStyles()
const jsModules = await ec.getJsModules()
const renderResult = await ec.render({
code: 'console.log("Hello world!")',
language: 'js',
meta: '',
})
// Output results to the console
console.dir({
baseStyles,
themeStyles,
blockStyles: renderResult.styles,
htmlContent: toHtml(renderResult.renderedGroupAst),
})
// Convert the rendered AST to HTML
let htmlContent = toHtml(renderResult.renderedGroupAst)
// Collect styles and add them before the HTML content
const stylesToPrepend = []
stylesToPrepend.push(baseStyles)
stylesToPrepend.push(themeStyles)
stylesToPrepend.push(...renderResult.styles)
const styleContent = `<style> ${[...stylesToPrepend].join('')} </style>`
const jsContent = `<script type="module"> ${[...jsModules].join('')} </script>`
const htmlDocument = `
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
${styleContent}
${jsContent}
</head>
<body>
${htmlContent}
</body>
</html>
`
// Output HTML to the console
console.log(htmlDocument)
// Run `node generate-html.mjs` to generate the HTML file
// and open it in the browser
fs.writeFileSync('index.html', htmlDocument)