背景

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.tsfunction 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.tsentry D:\wehotel-inspection\src\main.tslocalEnabled trueisDev trueenabled 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获取的