Giter VIP home page Giter VIP logo

vite-plugin-vconsole's Introduction

vite-plugin-vconsole

vite plugin for vconsole

A plugin for Vite v2+ that helps developers easily use the functions of VConsole in various environments.

English | 中文

Install (yarn or npm)

node version: >=12.0.0

vite version: >=2.0.0

# npm
npm i vite-plugin-vconsole -D
npm i  vconsole -S

# yarn
yarn add vconsole
yarn add vite-plugin-vconsole -D

# pnpm
pnpm add vconsole
pnpm add -D vite-plugin-vconsole

Example

# vue
cd ./example/vue-demo

yarn install

yarn dev
# react
cd ./example/react-demo

yarn install

yarn dev

Usage

Config plugin in vite.config.ts

  • Vue sample config
// tips: If the reference path hint does not exist, you can import the @types/node package
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import { viteVConsole } from 'vite-plugin-vconsole';
import * as path from 'path'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    viteVConsole({
      entry: path.resolve('src/main.ts'), // or you can use entry: [path.resolve('src/main.ts')]
      enabled: true,
      config: {
        maxLogNumber: 1000,
        theme: 'dark'
      }
    })
  ]
});
  • Vue sample config for multi pages
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import { viteVConsole } from 'vite-plugin-vconsole';
import * as path from 'path'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    viteVConsole({
      entry: [path.resolve('src/main.ts')], // entry for each page, different from the above
      enabled: true,
      config: {
        maxLogNumber: 1000,
        theme: 'dark'
      }
    })
  ]
});
  • React sample config
import { defineConfig } from 'vite';
import reactRefresh from '@vitejs/plugin-react-refresh';
import { viteVConsole } from 'vite-plugin-vconsole';
import * as path from 'path';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    reactRefresh(),
    viteVConsole({
      entry: path.resolve('src/main.tsx'),
      enabled: true,
      config: {
        maxLogNumber: 1000,
        theme: 'dark'
      }
    })
  ]
});
  • Different from the production environment and development environment
// Different from the production environment and development environment
// You can use command / mode to distinguish usage
import { UserConfigExport, ConfigEnv } from 'vite';
import { viteVConsole } from 'vite-plugin-vconsole';
import vue from '@vitejs/plugin-vue';
import * as path from 'path'

export default ({ command, mode }: ConfigEnv): UserConfigExport => {
  return {
    plugins: [
      vue(),
      viteVConsole({
        entry: [path.resolve('src/main.ts')], // entry file
        enabled: command !== 'serve' || mode === 'test', // build production
        config: { // vconsole options
          maxLogNumber: 1000
          theme: 'light'
        }
      })
    ],
  };
};
  • vConsole plugin config
viteVConsole({
  entry: path.resolve('src/main.ts'),
  enabled: true,
  config: {
    theme: 'dark',
    onReady() {
      console.log(23333);
    }
  },
  plugin: [
    {
      id: 'my_plugin',
      name: 'MyPlugin',
      event: [
        {
          eventName: 'init',
          callback: function () {
            console.log('My plugin init');
          }
        },
        {
          eventName: 'renderTab',
          callback: function () {
            console.log('My plugin renderTab');
          }
        }
      ]
    },
    {
      id: 'my_plugin2',
      name: 'MyPlugin2',
      event: [
        {
          eventName: 'init',
          callback: function () {
            console.log('My plugin2 init');
          }
        },
        {
          eventName: 'renderTab',
          callback: function () {
            console.log('My plugin2 renderTab');
          }
        }
      ]
    }
  ]
})

viteVConsole Options

/// <reference types="vconsole" />

{
  entry: string | string[]; // entry file require
  enabled?: boolean;
  config?: VConsoleOptions
  plugin?: {
    id: string;
    name: string;
    event: {
      eventName: string;
      callback: (data?: any) => void;
    }[]
  }[]
}
// customHide: A piece of executable code, used to start some APIs on the browser side.
viteVConsole({
  entry: path.resolve('src/main.ts'),
  enabled: true,
  customHide: `/iphone/g.test(navigator.userAgent.toLowerCase())`,
  config: {
    theme: 'dark',
    onReady() {
      console.log(23333);
    }
  },
})

Please note that the dynamic configuration here has the highest priority, and dynamicConfig will override the configuration in config.

You can provide a stringified runnable function that listens for a parameter as a trigger. Then modify a global variable window.vConsole.dynamicChange.value. When this variable changes, the dynamic configuration will take effect again. Here you can combine the above dynamic configuration to dynamically switch themes.

The reason why this design uses more stringified code is to reduce code intrusion into the production environment.

// Example, distinguish theme light and dark colors based on class
// Distinguish black or white based on whether it has a dark class name
viteVConsole({
  config: {
    theme: 'light'
  },
  dynamicConfig: {
    theme: `document.querySelectorAll('.dark').length ? 'dark' : 'light'`,
  },
  // If you need to switch themes without refreshing
  eventListener: `
    const targetElement = document.querySelector('body'); // Select the element to listen to
    const observerOptions = {
      attributes: true, // Listen for property changes
      attributeFilter: ['class'] // Only monitor class attribute changes
    };

    // Define callback functions to handle observed changes
    function handleAttributeChange(mutationsList, observer) {
      for(let mutation of mutationsList) {
        if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
          console.log('The class attribute was modified.');
          // Add the code you need to execute here
          if (window && window.vConsole) {
            window.vConsole.dynamicChange.value = new Date().getTime();
          }
        }
      }
    }

    // Create an observer instance and pass in the callback function
    const observer = new MutationObserver(handleAttributeChange);

    // Start observing the target element
    observer.observe(targetElement, observerOptions);

    // Stop observing when it is no longer needed
    // observer.disconnect();
  `,
})

Options

entry

type: string | string[] require:

must support. Supports multiple entries when it is an array.

enabled

type: boolean

default: true

config

type:: VConsoleOptions

plugin

type:

{
  id: string;
  name: string;
  event: {
    eventName: string;
    callback: (data?: any) => void;
  }[]
}[]

customHide

type:: String

Typescript

Add a reference to vconsole

/// <reference types="vconsole" />

dynamicConfig

Dynamic configuration items, which contain stringified functions. (It is recommended not to use dynamic configuration in production environments)

dynamicConfig: {
  theme?: string;
  target?: string;
  defaultPlugins?: string;
  disableLogScrolling?: boolean;
  pluginOrder?: string;
  log?: string;
  network?: string;
  storage?: string;
}

Here you can combine the following configurations to dynamically switch themes. Modifying a global variable window.vConsole.dynamicChange.value will trigger dynamic configuration reloading without refreshing the page.

eventListener

You can provide a stringified runnable function that listens for a parameter as a trigger. Then modify a global variable window.vConsole.dynamicChange.value. When this variable changes, the dynamic configuration will take effect again. Here you can combine the above dynamic configuration to dynamically switch themes.

eventListener?: string

Sample project

vite-vue-prod-template

Compatible to solve the Windows path problem

Update to V1.1.1+ version, Now you can use it normally in Windows.

Support multi-page configuration

Update to V1.2.0+ version, can support multi-page configuration.

Many thanks to @AfireHong for support!

Support VConsole Functions Configuration

Update to V1.3.0+ version, can support VConsole Functions Configuration.

Many thanks to @KeJunMao for support!

Support VConsole Plugin Configuration.Support custom destruction

Update to V2.0.0+ version, can support VConsole Plugin Configuration.Also supports custom destruction.

Support VConsole dynamic configuration. Support eventListener

Updated to version V2.1.0+, VConsole dynamic configuration can be configured. and you can give some eventListener code. It can be easily configured to follow theme changes, etc.

License

MIT

vite-plugin-vconsole's People

Contributors

afirehong avatar kejunmao avatar vadxq avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

vite-plugin-vconsole's Issues

build开启sourcemap,会有很多警告

警告如下:
Sourcemap is likely to be incorrect: a plugin (vite:vconsole) was used to transform files, but didn't generate a sourcemap for the transformation. Consult the plugin documentation for help

如何自定义vconsole插件

似乎被封死了?看仓库代码好像也不完整。
要怎么自定义vconsole的插件呢,或者获取vconsole自带面板的一些方法事件什么的?

error: [plugin externalize-deps] Failed

✘ [ERROR] [plugin externalize-deps] Failed to resolve entry for package "vite-plugin-vconsole". The package may have incorrect main/module/exports specified in its package.json.

VITE v3.1.8
node v14.19.0

为什么只允许 pnpm ?

package.json 中的脚本 preinstall": "npx only-allow pnpm导致报错,我并没有安装 pnpm,为什么要强制使用 pnpm

参数设计的让人很费解

enabledlocalEnabled 看了源码才知道分别是生产环境跟开发环境是否启用的配置,个人建议可以把这两个配置项合并成enableMode 字段以便跟 vite 对齐。

或者干脆取消,让用户自己在 vite 配置中根据 mode 判断是否加载插件。

内部判断太隐晦了:

const enabledTruly = (localEnabled && isDev) || (enabled && !isDev);

customHide参数的判断时机可以适当提前

我认为传递了customHide参数通常是不需要生成vconsole的,也就是不调用new VConsole,而不是通过使用vConsole.destroy()去销毁
当前vconsole使用destory会造成后续报错
Uncaught TypeError: Cannot read properties of undefined (reading 'update')
at u2 (vconsole.min.js:10:91405)
at e2._flushLogs (vconsole.min.js:10:91641)
at vconsole.min.js:10:91147

如何判断页面userAgent来选择是否加载vconsole

在pc电脑端调试的时候,不希望有vconsole,因为vconsole会拦截console的log信息,不便于定位代码。
但是vite的配置文件中,启动的时候无法拿到浏览器的userAgent,这个问题怎么解决,只能是页面打开的时候再去判断是否初始化vconsole了吗

动态显示vconsole

在生产环境,打包后会将vconsole的js文件一起打包吗?生产环境如何做到根据条件动态加载显示vconsole?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.