关于vite:vitepluginvconsole在windows不生效的原因排查

13次阅读

共计 2251 个字符,预计需要花费 6 分钟才能阅读完成。

背景

Vite 应用vConsole,不便挪动端的本地开发。官网文档见这里:https://github.com/vadxq/vite…。

场景复现

windows 客户端
“vite-plugin-vconsole”: “^1.1.0”
“vite”: “^2.7.0”,
“vconsole”: “^3.9.5”,
node v12.18.3
yarn 1.22.15
vite.config.js 配置如下:

import {resolve} from 'path';
...
viteVConsole({entry: resolve(__dirname, './src/main.ts'), // entry file
        localEnabled: mode !== 'prod', // dev environment
        enabled: mode !== 'prod', // build production
        config: {
          // vconsole options
          maxLogNumber: 1000,
          theme: 'light'
        }
})
...

尝试计划

  1. 认为本人配置错了。重复比照官网配置和他人的模板,没有谬误。
  2. 跑一下他人搭建好的模板。也是不失效。
  3. 谷歌搜寻过关键字,依然没有人提出
  4. 官网 github issue 也没有人提出

源码剖析

间接关上 vite-plugin-vconsole 的源码

"use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/index.ts
function viteVConsole(opt) {
  let viteConfig;
  let isDev = false;
  const {entry, enabled = true, localEnabled = false, config = {}} = opt;
  return {
    name: "vite:vconsole",
    enforce: "pre",
    configResolved(resolvedConfig) {
      viteConfig = resolvedConfig;
      isDev = viteConfig.command === "serve";
    },
    transform(_source, id) {if (id === entry && localEnabled && isDev) {return `${_source};import VConsole from 'vconsole';new VConsole(${JSON.stringify(config)});`;
      }
      if (id === entry && enabled && !isDev) {return `${_source};import VConsole from 'vconsole';new VConsole(${JSON.stringify(config)});`;
      }
      return _source;
    }
  };
}


exports.viteVConsole = viteVConsole;

看了下源码,总体来说很简略,就是依据一些参数判断,而后把 vConsole 新建实例的源码注入。目前没有失效,所以就要看看参数哪里对不上,于是献上 console 大法

 transform(_source, id) {console.log('id', id)
      console.log('entry', entry)
      console.log('localEnabled', localEnabled)
      console.log('isDev', isDev)
      console.log('enabled', enabled)
      console.log('_source', _source)
      if (id === entry && localEnabled && isDev) {return `${_source};import VConsole from 'vconsole';new VConsole(${JSON.stringify(config)});`;
      }
      if (id === entry && enabled && !isDev) {return `${_source};import VConsole from 'vconsole';new VConsole(${JSON.stringify(config)});`;
      }
      return _source;
    }

执行的后果

id D:/wehotel-inspection/src/main.ts
entry D:\wehotel-inspection\src\main.ts
localEnabled true
isDev true
enabled true

能够看到,id≠entry,原本 id 是 unix 零碎的正斜杠格局,咱们的 entry 是通过 path 的 resolve 性能解析失去的 windows 的反斜杠格局,所以咱们只须要把 path 解析的后果,转换成正斜杠就能够了

解决方案

用正则来替换就能够了:

viteVConsole({entry: resolve(__dirname, './src/main.ts').replace(/\\/g, '/'), // entry file
        localEnabled: mode !== 'prod', // dev environment
        enabled: mode !== 'prod', // build production
        config: {
          // vconsole options
          maxLogNumber: 1000,
          theme: 'light'
        }
      }),

其余

补充一下,import {resolve} from 'path'是通过装置这个包 @types/node 获取的

正文完
 0