vite-pwa / vitepress

Zero-config PWA Plugin for VitePress
https://vite-pwa-org.netlify.app/frameworks/vitepress
MIT License
36 stars 2 forks source link

After wrapping defineConfig with withPwa, I can't get defineConfig in other ts files #33

Closed hr1201 closed 3 months ago

hr1201 commented 5 months ago
import type { Plugin,UserConfig } from 'vitepress'
import { generateSidebar } from './sidebar';
import defineConfig from '../config';

export const FileHMR = (): Plugin => {
    return {
        name: 'vite-file-hmr',
        configureServer({
            watcher,
            restart
        }) {
            const fsWatcher = watcher.add('*.md');
            fsWatcher.on('all', async (event: string, path: string) => {
                if (event !== 'change') {
                    try {
                        (defineConfig as UserConfig).themeConfig.sidebar = generateSidebar()
                        await restart();
                    } catch (error: any){
                        console.log("🚀 ", (defineConfig as UserConfig).themeConfig)
                        console.log(error)
                    }
                }
            });
        },
    }
}

generatesidebar() is used to automatically generate the configuration structure of sidebar, so sidebar will not be updated automatically when vite changes the file, so I use the above code for hot update, but I can't get sidebar after wrapping defineConfig withPwa.

image

brc-dd commented 5 months ago

Can you show the code in your config file imported there? It won't work this way because withPwa(defineConfig({ ... })) will return a function-style config not an object.

hr1201 commented 5 months ago

my config file:

import { defineConfig } from "vitepress";
import { SitemapStream } from "sitemap";
import { createWriteStream } from "node:fs";
import { resolve } from "node:path";
import { nav } from "./configs/nav";
import { sidebar } from "./configs/sidebar";
import { FileHMR } from "./configs/watchfiles";
import { withPwa } from "@vite-pwa/vitepress";

interface Link {
  url: string;
  lastmod: number | undefined;
}

const links: Link[] = [];

export default withPwa(
  defineConfig({
    title: "Rarrot",
    description: "Rarrot",
    head: [
      ["link", { rel: "icon", href: "/favicon.ico" }],
      [
        "meta",
        { name: "baidu-site-verification", content: "codeva-90hqhBZdbA" },
      ],
    ],
    lastUpdated: true,
    // cleanUrls: true,

    markdown: {
      lineNumbers: true,
      // https://github.com/shikijs/shiki/blob/main/docs/themes.md#all-themes
      // theme: 'one-dark-pro',
      math: true,
    },

    transformHtml: (_, id, { pageData }) => {
      if (!/[\\/]404\.html$/.test(id)) {
        links.push({
          url: pageData.relativePath
            .replace(/\/index\.md$/, "/")
            .replace(/\.md$/, ".html"),
          lastmod: pageData.lastUpdated,
        });
      }
    },
    buildEnd: async ({ outDir }) => {
      const sitemap = new SitemapStream({
        hostname: "https://www.rorrot.cc/",
      });
      const writeStream = createWriteStream(resolve(outDir, "sitemap.xml"));
      sitemap.pipe(writeStream);
      links.forEach((link) => sitemap.write(link));
      sitemap.end();
      await new Promise((r) => writeStream.on("finish", r));
    },

    themeConfig: {
      // logo: {
      //   light: '/logo-light.svg',
      //   dark: '/logo-dark.svg',
      // },
      logo: "/titleImg-120.png",

      // https://vitepress.dev/reference/default-theme-config
      footer: {
        message: "Released under the MIT License.",
        copyright: `Copyright © 2023.4-${new Date().getFullYear()}.${
          new Date().getMonth() + 1
        }`,
      },
      algolia: {
        appId: "A5NVAQQUEO",
        apiKey: "fa9cdd39aee827af75ca9ead469cec1b",
        indexName: "rorrot",
      },

      socialLinks: [
        { icon: "discord", link: "https://discord.gg/Bad7NNcr" },
        { icon: "github", link: "https://github.com/hr1201" },
        { icon: "twitter", link: "https://twitter.com/hungrng75647520" },
        // {
        //  icon: {
        //   svg: '<svg role="img" viewBox="0 0 24 24" xmlns="SVG namespace"><title>Dribbble</title><path d="M12...6.38z"/></svg>',
        //  },
        //  link: "...",
        // },
      ],
      nav: nav,
      sidebar: sidebar,
    },
    vite: {
      plugins: [FileHMR()],
    },
    pwa: {
      outDir: ".vitepress/dist", 
      registerType: "autoUpdate", 
      includeManifestIcons: false,
      manifest: {
        id: "/", 
        name: "Rarrot_blog",
        short_name: "blog",
        description: "blog",
        theme_color: "#ffffff",
        icons: [
          {
            src: "/titleImg-120.png", 
            sizes: "120x120",
            type: "image/png",
          },
          {
            src: "/titleImg-192.png",
            sizes: "192x192",
            type: "image/png",
          },
          {
            src: "titleImg-512.png",
            sizes: "512x512",
            type: "image/png",
            purpose: "any",
          },
        ],
      },
      workbox: {
        globPatterns: ["**/*.{css,js,html,svg,png,ico,txt,woff2}"],
        runtimeCaching: [
          {
            urlPattern: /^https:\/\/fonts\.googleapis\.com\/.*/i,
            handler: "CacheFirst", 
            options: {
              cacheName: "google-fonts-cache", 
              expiration: {
                maxEntries: 10, 
                maxAgeSeconds: 60 * 60 * 24 * 365,
              },
              cacheableResponse: {
                statuses: [0, 200], 
              },
            },
          },
          {
            urlPattern: /^https:\/\/fonts\.gstatic\.com\/.*/i, 
            handler: "CacheFirst", 
            options: {
              cacheName: "gstatic-fonts-cache", 
              expiration: {
                maxEntries: 10, 
                maxAgeSeconds: 60 * 60 * 24 * 365,
              },
              cacheableResponse: {
                statuses: [0, 200],
              },
            },
          },
          {
            urlPattern: /^https:\/\/cdn\.jsdelivr\.net\/.*/i,
            handler: "NetworkFirst",
            options: {
              cacheName: "jsdelivr-images-cache", 
              expiration: {
                maxEntries: 10,
                maxAgeSeconds: 60 * 60 * 24 * 7,
              },
              cacheableResponse: {
                statuses: [0, 200], 
              },
            },
          },
        ],
      },
    },
  })
);

Yes,so I want to know how I can get sidebar and change it dynamically.I will appreciate that if you can tell me the answer.

Can you show the code in your config file imported there? It won't work this way because withPwa(defineConfig({ ... })) will return a function-style config not an object.

hr1201 commented 3 months ago

Now I have found a solution, thank you for your help.

const isProduction = process.env.NODE_ENV === 'production';

let config = defineConfig({
  title: 'Rarrot',
  description: 'Rarrot的个人博客网站',
  ...
});
if (isProduction) {
  config = await withPwa(config) as UserConfig<DefaultTheme.Config>;
}

export default config;

I can use this method because I don't need to dynamically change the sidebar in the production environment.Thank you again.