antfu-collective / vite-plugin-inspect

Inspect the intermediate state of Vite plugins
MIT License
1.29k stars 75 forks source link

Transform stack for custom virtual modules are not present #98

Closed Malien closed 7 months ago

Malien commented 1 year ago

Describe the bug

I have a custom loader that intercepts funky-looking import specifiers, ala: import foo from "prefix:some-argument".

const prefix = "custom-loader:";

export default function customLoader() {
  return {
    name: "custom-loader",

    resolveId(id) {
      if (id.startsWith(prefix)) return "\0" + id;
    },

    load(id) {
      if (!id.startsWith("\0")) return;
      if (!id.slice(1).startsWith(prefix)) return;
      const arg = id.slice(1 + prefix.length);
      return `export default ${JSON.stringify(arg)}`;
    },
  };
}

vite.config.js

import { defineConfig } from "vite";
import customLoader from "./custom-loader.mjs";
import Inspect from "vite-plugin-inspect";

export default defineConfig({
  plugins: [customLoader(), Inspect()],
});

As per rollup convention:

If your plugin uses 'virtual modules' (e.g. for helper functions), prefix the module ID with \0. This prevents other plugins from trying to process it.

But the transform stack of such virtual modules are empty (aka. I cannot see the result of a load step) Screenshot 2023-10-05 at 18 28 09

Reproduction

https://stackblitz.com/edit/vitejs-vite-g5udhe?file=custom-loader.mjs

System Info

System:
    OS: Linux 5.0 undefined
    CPU: (8) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
    Memory: 0 Bytes / 0 Bytes
    Shell: 1.0 - /bin/jsh
  Binaries:
    Node: 18.18.0 - /usr/local/bin/node
    Yarn: 1.22.19 - /usr/local/bin/yarn
    npm: 9.4.2 - /usr/local/bin/npm
    pnpm: 8.6.12 - /usr/local/bin/pnpm

Used Package Manager

pnpm

Validations

spaceemotion commented 8 months ago

Just stumbled upon this as well. As a workaround i have to use a simple console.log in the meantime.

justin-schroeder commented 7 months ago

Interesting — I just ran a quick trace on this and it seems the hijack for load doesn’t work on custom virtual modules. The result of this line is null:

https://github.com/antfu/vite-plugin-inspect/blob/main/src/node/hijack.ts#L104

userquin commented 7 months ago

The virtual module content not added to the recorder since the rollup filter is returning false: we need to apply the filter in resolveId hook, the filter should be applied to the original id and not to the resolved id.

userquin commented 7 months ago

Playground working after updating to latest 0.8.4 release: https://stackblitz.com/edit/vitejs-vite-qu7ibm?file=package.json,vite.config.js