Giter VIP home page Giter VIP logo

vite-plugin-vue-inspector's Introduction

vite-plugin-vue-inspector

NPM Version NPM Downloads License

📖 Introduction

A vite plugin which provides the ability that to jump to the local IDE when you click the element of browser automatically. It supports Vue2 & 3 & SSR.

vite-plugin-vue-inspector

📦 Installation

# vite-plugin-vue-inspector 

pnpm install vite-plugin-vue-inspector -D

# unplugin-vue-inspector

pnpm install unplugin-vue-inspector -D

🦄 Usage

Configuration Vite

// for Vue2

import { defineConfig, } from 'vite'
import { createVuePlugin, } from 'vite-plugin-vue2'
import Inspector from 'unplugin-vue-inspector/vite' // OR vite-plugin-vue-inspector

export default defineConfig({
  plugins: [
    createVuePlugin(),
    Inspector({
      vue: 2
    }),
  ],
})
// for Vue3

import { defineConfig } from 'vite'
import Vue from '@vitejs/plugin-vue'
import Inspector from 'unplugin-vue-inspector/vite' // OR vite-plugin-vue-inspector

export default defineConfig({
  plugins: [Vue(), Inspector()],
})
// for Nuxt3
// nuxt.config.ts
import { defineNuxtConfig } from 'nuxt/config'
import Inspector from 'vite-plugin-vue-inspector'

export default defineNuxtConfig({
  modules: [
    ['unplugin-vue-inspector/nuxt', {
      enabled: true,
      toggleButtonVisibility: 'always',
    }],
  ],
})

Options

interface VitePluginInspectorOptions {
  /**
  * Vue version
  * @default 3
  */
  vue?: 2 | 3

  /**
  * Default enable state
  * @default false
  */
  enabled?: boolean

  /**
  * Define a combo key to toggle inspector
  * @default 'control-shift' on windows, 'meta-shift' on other os
  *
  * any number of modifiers `control` `shift` `alt` `meta` followed by zero or one regular key, separated by -
  * examples: control-shift, control-o, control-alt-s  meta-x control-meta
  * Some keys have native behavior (e.g. alt-s opens history menu on firefox).
  * To avoid conflicts or accidentally typing into inputs, modifier only combinations are recommended.
  * You can also disable it by setting `false`.
  */
  toggleComboKey?: string | false

  /**
  * Toggle button visibility
  * @default 'active'
  */
  toggleButtonVisibility?: 'always' | 'active' | 'never'

  /**
  * Toggle button display position
  * @default top-right
  */
  toggleButtonPos?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'

  /**
  * append an import to the module id ending with `appendTo` instead of adding a script into body
  * useful for frameworks that do not support trannsformIndexHtml hook (e.g. Nuxt3)
  *
  * WARNING: only set this if you know exactly what it does.
  */
  appendTo?: string | RegExp

  /**
   * Customize openInEditor host (e.g. http://localhost:3000)
   * @default false
   * @deprecated This option is deprecated and removed in 5.0. The plugin now automatically detects the correct host.
   */
  openInEditorHost?: string | false

  /**
   * disable inspector on editor open
   * @default false
   */
  disableInspectorOnEditorOpen?: boolean
}

Example

🔌 Configuration IDE / Editor

It uses an environment variable named VUE_EDITOR to specify an IDE application, but if you do not set this variable, it will try to open a common IDE that you have open or installed once it is certified.

For example, if you want it always open VS Code when inspection clicked, set export VUE_EDITOR=code in your shell.

VS Code

  • install VS Code command line tools, see the official docs install-vscode-cli

  • set env to shell, like .bashrc or .zshrc

    export VUE_EDITOR=code

VS Code with WSL (Windows)

  • add the configuration in the settings.json

  • restart the VS Code (All Windows should be closed to take effect)

{
  // other config...

  "terminal.integrated.env.linux": {
    "EDITOR": "code"
  }
}

WebStorm

  • just set env with an absolute path to shell, like .bashrc or .zshrc (only MacOS)

    export VUE_EDITOR='/Applications/WebStorm.app/Contents/MacOS/webstorm'

OR

  • install WebStorm command line tools

  • then set env to shell, like .bashrc or .zshrc

    export VUE_EDITOR=webstorm

Vim

Yes! you can also use vim if you want, just set env to shell

export VUE_EDITOR=vim

💡 Notice

  • [BREAKING CHANGE] From v1.0, enabled option default value changed from true to false .
  • It only work in develop mode .
  • It does not currently support Template Engine (e.g. pug) .

👨‍💻 Programmatic Usage

You can also use control inspector programmatically, by accessing the __VUE_INSPECTOR__ global variable.

import type { VueInspectorClient } from 'vite-plugin-vue-inspector'

const inspector: VueInspectorClient = window.__VUE_INSPECTOR__

if (inspector) {
  // enable inspector
  inspector.enable()
  // or
  inspector.disable()
}

🌸 Credits

This project is inspired by react-dev-inspector .

Partially implementation is inspired by vite-plugin-svelte-inspector .

🤖️ Analysis of Theory

[Chinese] 点击页面元素,这个Vite插件帮我打开了Vue组件

📄 License

MIT LICENSE

vite-plugin-vue-inspector's People

Contributors

a145789 avatar aki77 avatar antfu avatar ben avatar hanneskuettner avatar joshbmarshall avatar loongphy avatar marvinschuerz avatar melodyvoid avatar mini-ghost avatar samverschueren avatar sxzz avatar webfansplz avatar xinchou16 avatar zhangmo8 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  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  avatar  avatar  avatar

vite-plugin-vue-inspector's Issues

Unquoted attribute error

This is a really nice looking plugin, but it does not work for me.

I have tried adding it to my vite (v2.9.5) vue3 app and to storybook (vite then webpack), and both return the following error:

[vite] Internal server error: Unquoted attribute value cannot contain U+0022 ("), U+0027 ('), U+003C (<), U+003D (=), and U+0060 (`).
Plugin: vite-plugin-vue-inspector
File: @vue/compiler-core/dist/compiler-core.cjs.js:19:19

some suggestion

I've been using it for a while and have some experience suggestions

  1. The operation button is too big, please make it smaller. It would be better to have a little transparency in disabled state
  2. The image used for the button is from Github, but sometimes the connection is not smooth, so it cannot be loaded

Thanks for developing this plugin

最新版windows系统无法使用

vue2 windows系统使用3.0.0版本的没效果
0.2.6版本可以使用

看了下属性和交互代码注入到页面了 但是没出来悬浮框 点击也没效果

Cannot read properties of undefined (reading 'browserHash')

I have just tried using the latest version 0.2.5, but got the following error:

3:26:36 PM [vite] Internal server error: Cannot read properties of undefined (reading 'browserHash')
      at transformIndexHtml (/home/bodo/proj/node_modules/vite-plugin-vue-inspector/dist/index.js:538:48)
      at applyHtmlTransforms (/home/bodo/proj/node_modules/vite/dist/node/chunks/dep-611778e0.js:27150:27)
      at processTicksAndRejections (node:internal/process/task_queues:96:5)
      at async viteIndexHtmlMiddleware (/home/bodo/proj/node_modules/vite/dist/node/chunks/dep-611778e0.js:55903:28)

I am also using vite-plugin-html-2.1.2. Maybe there is a conflict?

load.js 404 not found

image

inspectorPath 有src后面有两个斜杠,id.startsWith无法匹配到。 难道以前的vite版本中没有处理双斜杠吗?

image

image

如上,手动inspectorPath.replace('//', '/') 后,可以正常使用了

vite v3.2.6

HMR not working

I created an empty project using pnpm create vite and then installed vite-plugin-vue-inspector and found that HMR doesn't work.

toggleEventListener runtime error

Our project use element-ui, and it hack eventlistener, while overlay.vue js code bind event listener whithou check this

element-ui

var hackEventListener = () => {
  Element.prototype._addEventListener = Element.prototype.addEventListener;
  Element.prototype._removeEventListener = Element.prototype.removeEventListener;
  Element.prototype.addEventListener = function(type, listener, useCapture = false) {
    this._addEventListener(type, listener, useCapture);
    if (!this.__eventListenerList__) {
      this.__eventListenerList__ = {};
    }
    if (!this.__eventListenerList__[type]) {
      this.__eventListenerList__[type] = [];
    }
    this.__eventListenerList__[type].push({ type, listener, useCapture });
  };
  Element.prototype.removeEventListener = function(type, listener, useCapture = false) {
    this._removeEventListener(type, listener, useCapture);
    //...
  }

overlay.vue

toggleEventListener() {
      const listener = this.enabled ? document.body.addEventListener : document.body.removeEventListener
      listener?.('mousemove', this.updateLinkParams)
      listener?.('click', this.handleClick, true)
    },

定位不到有关业务文件

假设
A:业务页面
B:布局组件(插槽)
C:功能性组件

A 引用了 B, 在B的插槽里,使用C
最想定位的是A组件,A是有关业务的代码,B和C是被封装的组件一般不需要定位
我试的结果是,定位不到A,只能定位到B和C

Network Error

Because inspectorOptions.serverOptions?.host can be true,so the final baseUrl will be something like https://true:3000/open-stack-frame-in-editor, then lead to a network error:

const isClient = typeof window !== "undefined"
const importMetaUrl = isClient ? new URL(import.meta.url) : {}
const protocol = inspectorOptions.serverOptions?.https ? "https:" : importMetaUrl?.protocol
const host = inspectorOptions.serverOptions?.host ?? importMetaUrl?.hostname
const port = inspectorOptions.serverOptions?.port ?? importMetaUrl?.port
const baseUrl = isClient ? `${protocol}//${host}:${port}` : ""

image

"Illegal tag name. Use '&lt;' to print '<'." In Nuxt3+pug

Hello!

There's an error in pug:

<template lang="pug">
span(v-if="idx < last_idx")
</template>

This code leads to Illegal tag name. Use '&lt;' to print '<'. error.

However, the code is correct as < sign is used inside a js template.

More Clear Key Name

Press Meta+Shift in App to toggle the Inspector

There's no actually a key called Meta on the physical keyboard. So could change it to ⌘ Command + ⇧ Shift on macOS and Alt + Shift on Windows (IIRC)

Quasar framework problem

Plugin doesn't works with Quasar
error is: GET http://0.0.0.0:9300/__open-in-editor?file=AppLibrary\libFront\GlobalComponents\HomeComp.vue:2:3 net::ERR_ADDRESS_INVALID.

As I see the problem is in url 0.0.0.0:9300

When I send GET localhost:5173/__open-in .... from Postman, component is opened in VSC.
Maybe it's Quasar problem

Issue to add plugin

Hi,
on a project ts vite v2.9 vue v.3.2 adding the plugin on vite.config.ts as is :

 plugins: createVitePlugins(viteEnv, isBuild, prodMock),

where createVitePlugins is

import Inspector from "vite-plugin-vue-inspector"
export function createVitePlugins(viteEnv: ViteEnv, isBuild: boolean, prodMock) {
...
    const vitePlugins: (Plugin | Plugin[])[] = [
    vue(),
    vueJsx(),
...
    Inspector()        < here the problem 
 ];
 ...

I have this error :

(alias) Inspector(options?: VitePluginInspectorOptions | undefined): PluginOption
import Inspector
Type 'PluginOption' is not assignable to type 'Plugin | Plugin[]'.
  Type 'undefined' is not assignable to type 'Plugin | Plugin[]'.ts(2322)

How to add the plugin using this mode ?

Thanks in advance

Disable button

Hey!

Is there a way to disable the button functionality by default, everytime I refresh the page, the button is enable so I have to manually disable it so I can interact with my app

Windows Usage

How to use this vite plugin in windows OS ?

I tried both ways

  1. command line set env
  2. Edit the system environment variables

Screenshot (120)


defaultEditor option in vite would be so helpfull instead of setting env

Inspector({
    enabled: true,
    defaultEditor: 'code'
})

Thanks

does not provide an export named 'render'

环境win10,vue2,vite3

  • vite:3.1.3
  • vite-plugin-vue2:2.0.2
    配置文件如下,
const config = (mode) => {
  const envConfig = loadEnv(mode, process.cwd());
  return defineConfig({
    resolve: {
      plugins: [
        createVuePlugin({ jsx: true }),
        Inspector({
          vue: 2,
        }),
      ],
    }
  });
};

启动后打开页面,控制台有如下报错
65473B8E-7578-47ef-A6FF-3603FDA2EB10
我试了一下vite2是正常的,在3里面会有这个报错

Support for docker containers

The inspector does not work when using a vite server running inside a docker container because the inspector attempts to open the editor within the context of the docker shell.

I've read that it's possible to configure command execution on the host from the container, but it seems cumbersome and potentially opens a major security vulnerability in the host machine.

Do you have any ideas about how this can be supported?

Doesn't work if Vite has a base configured

My project runs in dev mode against Foundry VTT, and Vite's base is configured as /systems/foundry-ironsworn/. This works when the Vite app isn't serving the whole app, only parts of it.

But when I try to use the inspector, the URL it tries to visit looks like this:

http://localhost:8080/__open-in-editor?file=src/...

That doesn't work, because that path gets proxied to the underlying app. If I visit this URL directly:

http://localhost:8080/systems/foundry-ironsworn/__open-in-editor?file=src/...

Then it works properly. Looks like this plugin needs to include Vite's base configuration in this place in the code.

[Bug] Does not recognize a component unless it has a root element

It seems that it does not recognize a component unless I add a root element wrapper like a <div> and then it works.

For example, if my component looks like this, then it does not recognize it:

<template>
  <PrimeDropdown
     v-model="appStore.locale"
     :options="locales"
  />
</template>

But if I add a root <div> then it is recognized:

<template>
+  <div>
     <PrimeDropdown
        v-model="appStore.locale"
        :options="locales"
      />
+  </div>
</template>

vue: 3.2.37
vite: 3.0.7
vite-plugin-vue-inspector: 3.3.0

Here is a screencast demo where you can see that as I hover over the Language Switcher it does not recognize it:

Kazam_screencast_00047.mp4

Windows vscode remote usage

Hi,

I have a problem. This solution doesnt work with remote dev on SSH session on VScode.

I run the npm run dev command in a bash opened in VScode but when i click on a compoenent in the browser it open the file in vim instead of Vscode.

Has anyone had the problem before?

Thanks in advance

Failed to start Vite dev server

Error log:

failed to load config from /root/dev/web/daotl-vitesse/vite.config.ts
error when starting dev server:
file:///root/dev/web/daotl-vitesse/node_modules/.pnpm/[email protected][email protected]/node_modules/vite-plugin-vue-inspector/dist/index.mjs:32
import { parse as babelParse, traverse as babelTraverse } from "@babel/core";
                              ^^^^^^^^
SyntaxError: Named export 'traverse' not found. The requested module '@babel/core' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from '@babel/core';
const { parse: babelParse, traverse: babelTraverse } = pkg;

    at ModuleJob._instantiate (node:internal/modules/esm/module_job:123:21)
    at async ModuleJob.run (node:internal/modules/esm/module_job:189:5)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:527:24)
    at async loadConfigFromBundledFile (file:///root/dev/web/daotl-vitesse/node_modules/.pnpm/[email protected]/node_modules/vite/dist/node/chunks/dep-c842e491.js:64010:21)
    at async loadConfigFromFile (file:///root/dev/web/daotl-vitesse/node_modules/.pnpm/[email protected]/node_modules/vite/dist/node/chunks/dep-c842e491.js:63895:28)
    at async resolveConfig (file:///root/dev/web/daotl-vitesse/node_modules/.pnpm/[email protected]/node_modules/vite/dist/node/chunks/dep-c842e491.js:63519:28)
    at async createServer (file:///root/dev/web/daotl-vitesse/node_modules/.pnpm/[email protected]/node_modules/vite/dist/node/chunks/dep-c842e491.js:62819:20)
    at async CAC.<anonymous> (file:///root/dev/web/daotl-vitesse/node_modules/.pnpm/[email protected]/node_modules/vite/dist/node/cli.js:707:24)
 ELIFECYCLE  Command failed with exit code 1.

Replace error

s.replace(/(createElementVNode|createVNode|createElementBlock) as _\1,?/g, (_, name) => {
fn.add(name)
return ''
})
if (!fn.size)
return
s.appendLeft(0, `/* Injection by vite-plugin-vue-inspector Start */
import { ${Array.from(fn.values()).map(i => `${i} as __${i}`).join(',')} } from 'vue'
function _interopVNode(vnode) {
if (vnode && vnode.props && 'data-v-inspector' in vnode.props) {
const data = vnode.props['data-v-inspector']
delete vnode.props['data-v-inspector']
Object.defineProperty(vnode.props, '__v_inspector', { value: data, enumerable: false })
}
return vnode

before:

import { createTextVNode as _createTextVNode2, createVNode as _createVNode2, resolveComponent as _resolveComponent2 } from "vue";

after:

...
function _createVNode(...args) { return _interopVNode(__createVNode(...args)) }
...
import { createTextVNode as _createTextVNode2, 2, resolveComponent as _resolveComponent2 } from "vue";

可能是由于对于部分组件文件使用jsx,导致的打包时重复引入,对于_createVNode2的别名情况未处理

Support Overlay separation

vite-plugin-vue-inspector provides me with great development experience.

But sometimes, I have to obtain the position information of the node element on the source code at runtime (after the product is released) to locate the code that causes the problem quickly.

Overlay is an enhancement to the development experience, and it should also be a feature that can be discarded in other modes.

can we disable combo key when `toggleComboKey` is `false` or empty string

Maybe we can disable combo key via set toggleComboKey is false or empty string or other?

In currently, we set toggleButtonVisibility: 'always' so we hope we can disable combo key to toggle inspector. But it will throw an error when we set toggleButtonVisibility an empty string and run pnpm dev.

Opens nano even VUE_EDITOR is set to phpstorm

I've tried exporting the variable in .zshrc

export VUE_EDITOR=/usr/local/bin/phpstorm

and also

export VUE_EDITOR=phpstorm

but it opens the file in nano in the terminal emulator from which it was started.

I'm using:

OS: Arch Linux
DE: Gnome 44
TE1: Terminator - installed from official Arch repo (not flatpak or something else)
TE2: Gnome Terminal - installed from official Arch repo (not flatpak or something else)
IDE: PHPStorm - installed as binary from JetBrains

Any suggestions on what should I try?

Hide in Vue devtools

Since most people will probably use this plugin alongside the Vue devtools it would be nice to hide the app in the Vue devtools, to not clutter the listed apps.

This can be done by exporting the following in the Overlay.vue component.

export default {
   devtools: { hide:  true }
}

所有文件有下划线的都无法打开

比如: /#/scrm/setting/sales_workflow 网络会发送成
/__open-stack-frame-in-editor?file=src\views\scrm\setting\sales&line=workflow\List.vue&column=24
很明显, 下划线的截取除了问题, sales_workflow 这个单词被 _ 下划线 截断了

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.