You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在dev模式下调试vite-plugin-static-copy的transform函数?

问题:vite-plugin-static-copy的transform函数无日志输出

从webpack的copyWebpackPlugin迁移到vite-plugin-static-copy后,执行npm run dev时,transform函数内的所有console.log(包括processJson中的日志)都没有输出,仅能看到[vite-plugin-static-copy] Collected 1 items.的提示。

以下是当前的vite.config.ts配置:

import { defineConfig } from 'vite';
import preact from '@preact/preset-vite';
import ssr from 'vike/plugin';
import { viteStaticCopy } from 'vite-plugin-static-copy'

export default defineConfig({
  plugins: [
    preact(),
    ssr({ prerender: true }),
    viteStaticCopy({
      targets: [
        {
          src: 'public/assets/icons/favicon.svg', // 占位文件,仅用于触发脚本执行
          dest: `path/to/dir`,
          rename: 'filename.pdf',
          transform: {
            encoding: 'buffer',
            handler: async (_content, path) => {
              console.log(1)
              try {
                const response = await fetch(URL)
                const json = await response.json()

                console.log(json)
    
                return await processJson(json)
              } catch (e) {
                console.log(path)
                console.log(e)
              }
            },
          },
        }
      ]
    })
  ],
});

排查与解决步骤

  • 强制开启开发环境复制:vite-plugin-static-copy在dev模式下默认不会重复执行复制逻辑,需显式开启devCopy选项,确保开发环境下触发transform:
    viteStaticCopy({
      devCopy: true, // 新增此配置
      targets: [/* 原有目标配置 */]
    })
    
  • 验证源文件路径有效性:如果配置的src路径对应的文件不存在,插件会跳过该目标的处理。先替换为一个真实存在的测试文件,确认transform函数是否能被触发。
  • 优化日志输出方式:将普通console.log替换为console.error(错误场景)或确保同步日志优先执行,避免异步错误导致日志被吞:
    handler: async (_content, path) => {
      console.log('进入transform函数') // 同步日志,优先验证是否进入函数
      try {
        const response = await fetch(URL)
        const json = await response.json()
    
        console.log(json)
        return await processJson(json)
      } catch (e) {
        console.error('transform执行异常:', path, e) // 用error级别确保日志被显示
      }
    }
    
  • 调整Vite日志级别:如果Vite日志级别过高,可能会过滤掉调试日志。在配置中添加日志级别设置:
    export default defineConfig({
      logLevel: 'info', // 确保能显示插件的调试信息
      // ... 其他配置
    })
    
  • 隔离processJson函数:暂时将processJson(json)替换为简单的返回值(如return Buffer.from('test content')),验证是否是该函数内部错误导致日志中断。

内容的提问来源于stack exchange,提问作者RCKT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 15:45:10