vconsole.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import path from 'node:path'
  2. import { viteVConsole } from 'vite-plugin-vconsole'
  3. export function createViteVConsole() {
  4. return viteVConsole({
  5. entry: [path.resolve('src/main.ts')],
  6. enabled: false,
  7. config: {
  8. maxLogNumber: 1000,
  9. theme: 'light',
  10. },
  11. // https://github.com/vadxq/vite-plugin-vconsole/issues/21
  12. dynamicConfig: {
  13. theme: `document.documentElement.classList.contains('dark') ? 'dark' : 'light'`,
  14. },
  15. eventListener: `
  16. const targetElement = document.querySelector('html'); // 择要监听的元素
  17. const observerOptions = {
  18. attributes: true, // 监听属性变化
  19. attributeFilter: ['class'] // 只监听class属性变化
  20. };
  21. // 定义回调函数来处理观察到的变化
  22. function handleAttributeChange(mutationsList) {
  23. for(let mutation of mutationsList) {
  24. if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
  25. if (window && window.vConsole) {
  26. window.vConsole.dynamicChange.value = new Date().getTime();
  27. }
  28. }
  29. }
  30. }
  31. // 创建观察者实例并传入回调函数
  32. const observer = new MutationObserver(handleAttributeChange);
  33. // 开始观察目标元素
  34. observer.observe(targetElement, observerOptions);
  35. // 当不再需要观察时,停止观察
  36. // observer.disconnect();
  37. `,
  38. })
  39. }