vite-plugin / vite-plugin-dynamic-import

Enhance Vite builtin dynamic import
https://www.npmjs.com/package/vite-plugin-dynamic-import
MIT License
193 stars 11 forks source link

`// [vite-plugin-dynamic-import] runtime -S-` header missing in compiled source #64

Open shellscape opened 1 year ago

shellscape commented 1 year ago

Using createServer are there any scenarios where this plugin would not add // [vite-plugin-dynamic-import] runtime -S- to the compiled source code?

I'm running into a situation where this plugin seems to be outputting the // [vite-plugin-dynamic-import] runtime -S- header (and rest of the dynamic code) to the compiled files in some circumstances, but not others, using the same application code.

Have you seen this before?

caoxiemeihao commented 1 year ago

👋 Hey! @shellscape nice to meet you here. I'm not sure what your source code looks like, but this plugin will only fix some edge cases that Vite/Rollup can't handle (that would definitely have // [vite-plugin-dynamic-import] runtime -S-). If the importee part of import() in the source code can be correctly processed by Vite/Rollup, then // [vite-plugin-dynamic-import] runtime -S- will not be generated.

shellscape commented 1 year ago

Ah that's interesting. That would be a nice bit of info for the readme!

caoxiemeihao commented 1 year ago

In Vite, only if importee can be resolved normally by resolve(), it can be regarded as a valid import() statement. However, resolve() has many internal restrictions, which leads to the inability to handle many edge scenarios. .

image

source code is here 👉 https://github.com/vitejs/vite/blob/v4.4.11/packages/vite/src/node/plugins/dynamicImportVars.ts#L106-L109


I list some examples of what are considered "edge cases" that need to be handled by vite-plugin-dynamic-import.

// 1. Absolute path are confused with alias, `/root/src` is an alias.
import(`/root/src/views/${id}`)

// 2. Missing slash after `./views`
import(`./views${id}.tsx`)

// 3. Contains both aliases and operations
import('@/views/' + 'foo.js')

// 4. Only aliases and no file extension
import(`@/${id}`)

You can see them in the test files. 👉 test/fixtures/src/main.ts, and output is here 👉 test/fixtures/snapshots/main.ts