Skip to content

rspack/webpack virtual modules can't do relative import #483

@edemaine

Description

@edemaine

Environment

[email protected]
Node 23.4.0
Windows 11 version 10.0.26100 Build 26100

Reproduction

Repo: https://github.com/edemaine/unplugin-rspack-relative-import
Run:

  • npm install
  • npm run build

Error:

> [email protected] build
> rspack build

ERROR in ./node_modules/.virtual/C%3A%5CUsers%5Cedemaine%5CProjects%5Cunplugin-rspack-relative-import%5Csrc%5Cindex.civet.jsx 1:0-21
  × Module not found: Can't resolve './index.css' in 'C:\Users\edemaine\Projects\unplugin-rspack-relative-import\node_modules\.virtual'
   ╭─[1:7]
 1 │ import "./index.css";
   ·        ─────────────
 2 │
 3 │ document.querySelector("#root").innerHTML = `
   ╰────

Describe the bug

From #416 I gather that webpack/rspack virtual modules get put inside node_modules/.virtual. Then the relative import of ./index.css is getting resolved within that directory, which fails.

Additional context

I tried logging calls to resolveId, and I see the following:

resolveId("./src/index.civet", undefined)
resolveId("./index.css", "\C:\Users\edemaine\Projects\Civet\integration\unplugin-examples\rspack\src\index.civet.jsx")

This suggest to me that the virtual prefix is getting stripped incorrectly on Windows; I don't think the leading \ should be there. #421 might be the same issue, and #422 might fix this.

But I don't think that this is the cause for this particular bug. rspack itself isn't going to strip virtual module names; only unplugin will. So rspack is going to resolve relative paths incorrectly, unless they're handled by an unplugin. I'd rather not have my unplugin help resolve all files, only the ones it's supposed to do (.civet).

I guess the workaround is for my unplugin's resolveId to fix the paths for all imports, perhaps when the importer is recognized as something my unplugin generated.

I think a better fix would be to put virtual modules in the same directory as the source file. I understand that the node_modules/.virtual choice was made to avoid it appearing in VSCode or Git. But I don't see how relative imports could work in this scenario.

Let me know what you think and I can try to work on a fix.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingrspack

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions