避坑指南:我在使用vitepress时遇的坑

2,293 阅读1分钟

vitepress 打包遇到windows为undefiend的问题

原因是使用的组件中可能会使用windows全局变量,但vitepress打包的时候,会在node中执行(为了服务端渲染的场景),
node中没有window
第一种方案: 使用ClientOnly组件(仅在客户端渲染其插槽组件使用)  但是不建议
<ClientOnly>
  <NonSSRFriendlyComponent />
</ClientOnly>

第二种方案: 使用vue混入,在mounted中动态导入,
// \docs\.vitepress\theme\index.js
export default {
  ...DefaultTheme,
  NotFound: () => "custom 404", // <- this is a Vue 3 functional component
  enhanceApp: async (ctx) => {
    let { app } = ctx;
    DefaultTheme.enhanceApp(ctx);
    app.mixin({
      async mounted() {
        //你自己的插件地址
        import('../../src/index.js').then(module => {
            Vue.use(module.default);
        })
      },
    });
  },
};

vitepress里面写md的时候注意事项

如果你写md表格里面有特殊字符,比如 {}_ \等 需要使用转义符转移,否则会报错,示例如下,标记的地方

|插槽名称|说明|
|-|-|
|toolbar|数据表上方工具栏|
|fieldCode|自定义数据表单元格,作用域参数为  \{ row, column, $index \} |
|opreate|自定义固定在右侧的操作列,作用域参数为  \{ row, column, $index \} |



vitepress如果内部有引用的第三方库,会发送请求根目录下的包以及报错

image.png

image.png


// .vitepress\theme\config.js
module.exports = {
    // ....
     transformHtml(html) {
        return html.replace(
          '<head>',
          `<head><script type="importmap">{
            "imports": {
              "vue": "https://cdnjs.cloudflare.com/ajax/libs/vue/3.2.41/vue.esm-browser.prod.js",
              "vuedraggable":"https://tcwlservice.qa.17usoft.com/doc/v2/assets/vuedraggable.js",
              "element-plus":"https://tcwlservice.qa.17usoft.com/doc/v2/assets/element-plus.js"
            }
          }</script>`
        )
      },
}