如何在网页中展示源代码

如何在网页中展示你的源代码

如下图所示:

在做技术说明文档 或者 组件库 的时候,经常需要在网页中引用代码示例,但是直接写又很丑,所以我们来试试如何在网页中展示自己的源代码

第一步: 自定义 vite插件

首先需要一个自定义插件用来转换 vue 的自定义块

在vite.config.ts文件里

ts 复制代码
import fs from 'fs'
import {baseParse} from '@vue/compiler-core'
const vueDemoPlugin = {
	name: "vue-block-demo",
	transform(code, path) {
		if (!/vue&type=demo/.test(path)) {
			return;
		}
		const filePath = path.split("?")[0];
		//异步读取文件内容,并转为string类型
		const file = fs.readFileSync(filePath).toString();
		//将读取到的文件中的自定义快渲染为AST
		const parsed = baseParse(file).children.find((n) => n.tag === "demo");
		//读取自定义模块中的文本内容
		const title = parsed.children[0].content;
		//将读取文件中的自定义块切分,并转为字符串类型
		const main = file.split(parsed.loc.source).join("").trim();
		//以JSON数据类型返回
		return `export default Comp => {
			Comp.__sourceCode = ${JSON.stringify(main)}
			Comp.__sourceCodeTitle = ${JSON.stringify(title)}
		}`;
	},
};
export default defineConfig({
  plugins: [vue(), vueDemoPlugin],
})

第二步:在要展示的源代码文件里面加上一个自定义块

比如我要展示 SwitchDemo01.vue 文件

<template> 加上 <demo> 自定义块,里面内容写上 title

vue 复制代码
<demo>常规用法</demo>
<template>
    <hx-switch v-model="value1" />
    <hx-switch
      v-model="value2"
      class="ml-2"
      style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
    />
</template>
  
<script lang="ts" setup>
  import { HxSwitch } from 'hx-gulu-ui';
  import { ref } from 'vue'
  
  const value1 = ref(true)
  const value2 = ref(true)
</script>

第三步: 在页面展示文件里面引用

如: showSwitch.vue 文件:

vue 复制代码
<template>
    <div class="doc-page">
        <h2>Switch 组件示例 </h2>
        <p class="doc-page-desc">表示两种相互对立的状态间的切换,多用于触发「开/关」。</p>
        <div class="demo">
            <h3>{{ SwitchDemo01.__sourceCodeTitle }}</h3>
            <p class="doc-page-usage">绑定 `v-model` 到一个 `Boolean` 类型的变量。 可以使用 `--el-switch-on-color` 属性与 `--el-switch-off-color` 属性来设置开关的背景色</p>
            <div class="demo-component">
                <SwitchDemo01></SwitchDemo01>
            </div>
            <div class="demo-actions">
                <Button>查看代码</Button>
            </div>
            <div class="demo-code">
                <pre>{{ SwitchDemo01.__sourceCode }}</pre>
            </div>
        </div>

    </div>
</template>

<script lang="ts" setup>
import SwitchDemo01 from '@/components/switch/SwitchDemo01.vue'

// __sourceCode 这里面是源文件去除了 <demo> 外的所有代码
console.log('SwitchDemo01', SwitchDemo01.__sourceCode)

// __sourceCodeTitle 这里面是 <demo>常规用法</demo> 里面的文字
console.log('SwitchDemo01', SwitchDemo01.__sourceCodeTitle)

</script>

<style lang="scss" scoped>
@import './style.scss';

</style>

此时,已经可以在代码上显示源文件代码了,但是代码没有任何样式,很丑怎么办呢?

第四步: 引入 prismjs

  • prismjs 是代码主题的插件

    • 官网
    • 安装: npm i prismjs
  • 调用

    import 引入 好像有问题,只支持 require('prismjs'),同时在window属性下 添加了 Prismjs属性,大家可以自己试一下

    xml 复制代码
    <script setup lang='ts'>
        import 'prismjs'
        import 'prismjs/themes/prism-okaidia.min.css'
        const Prism = (window as any).Prism
        
        const code = `var data = 1;`;
        const html = Prism.highlight(code, Prism.languages.javascript, 'javascript');
    </script>

    示例:

vue 复制代码
<template>
   <div class="doc-page">
       <h2>Switch 组件示例 </h2>
       <p class="doc-page-desc">表示两种相互对立的状态间的切换,多用于触发「开/关」。</p>
       <div class="demo">
           <h3>{{ SwitchDemo01.__sourceCodeTitle }}</h3>
           <p class="doc-page-usage">绑定 `v-model` 到一个 `Boolean` 类型的变量。 可以使用 `--el-switch-on-color` 属性与 `--el-switch-off-color` 属性来设置开关的背景色</p>
           <div class="demo-component">
               <SwitchDemo01></SwitchDemo01>
           </div>
           <div class="demo-actions">
               <Button>查看代码</Button>
           </div>
           <div class="demo-code">
               <pre class="language-html" v-html="html"></pre>
           </div>
       </div>

   </div>
</template>

<script lang="ts" setup>
import SwitchDemo01 from '@/components/switch/SwitchDemo01.vue'

import 'prismjs'
import 'prismjs/themes/prism-okaidia.min.css'
const Prism = (window as any).Prism

const html = computed(() => {
   return Prism.highlight(SwitchDemo01.__sourceCode, Prism.languages.html, 'html') 
})

</script>

<style lang="scss" scoped>
@import './style.scss';

</style>

最终效果如下图所示:

相关推荐
你挚爱的强哥44 分钟前
Vue2 实现 1.5s 十连击监听(连续点击若干次),封装通用可复用点击检测工具,不用 data!Vue 封装通用连击监听方法,支持自定义时长与点击次数
前端·javascript·vue.js
卓怡学长2 小时前
w266基于spring boot + vue 圣地延安美食乐享系统
java·数据库·vue.js·spring boot·spring·intellij-idea
Random_index5 小时前
#Vue3篇: Vue 项目发版后如何提示用户刷新?基于 package.json 版本号的前端更新检测方案
前端·vue.js·json
用户83134859306986 小时前
Cesium自定义可调节星空夜景+星星闪烁
vue.js·cesium
白露与泡影7 小时前
用 Spring Boot + Vue + Fuzio 构建现代 Java 桌面应用
java·vue.js·spring boot
WindfallSheng8 小时前
从Vibe Coding到Spec Coding:一套可落地的AI-SDD企业级研发实战工程
javascript·vue.js
我有满天星辰9 小时前
Vue 指令完全指南:从 Vue 2 到 Vue 3 的演进与实战
前端·javascript·vue.js
我有满天星辰11 小时前
Vue 3 响应式双雄:ref 与 reactive 完全指南
前端·javascript·vue.js
leoZ2311 天前
Claude 驱动的全栈开发:Spring Boot + Vue 的 BS 架构实践
vue.js·spring boot·架构
荒诞英雄1 天前
从 17MB Vendor 大包到按需加载:Vite 多入口 Vue 组件库首屏优化实践
vue.js·vite