unimport
unimport copied to clipboard
Some imports in comments are taken into account
Environment
The issue has been reproduced in the following environment.
Reproduction
The simplest reproduction could look like this:
import { createUnimport } from 'unimport'
const { injectImports } = createUnimport({
imports: [{ name: 'store', from: 'module-store' }],
virtualImports: ['#imports'],
})
const input = "// import { store } from '#imports'"
const { code } = await injectImports(input)
console.log(code)
// import { store } from 'module-store';
// //
While, a more realistic reproduction would look like this:
import { createUnimport } from 'unimport'
const { injectImports } = createUnimport({
imports: [{ name: 'store', from: 'module-store' }],
virtualImports: ['#imports'],
})
const input = `export const store = {
/**
* @example
* import { store } from '#imports'
* store.fetch()
*/
fetch: () => {}
}`
const { code } = await injectImports(input)
console.log(code)
// import { store } from 'module-store';
// export const store = {
// /**
// * @example
// * * store.fetch()
// */
// fetch: () => {}
// }
Describe the bug
When unimport is given code with comments that include imports from virtual modules, those comments are taken into account to know whether imports should be injected or not.
In the reproduction above, we can see two things:
- The import from the comment section is removed.
- A new regular import is added at the top of the file.
In this specific scenario where comments are used to showcase how to use this piece of code, the result code will crash if executed. Indeed, there are now two variables with the same name:
- One from the import (
import { store } from '#imports'
). - One from the original code (
const store
).
From my understanding, I would expect imports in comments not to be taken into account when figuring out whether imports should be injected or not.
Additional context
I tracked this issue down from a Nuxt application where I first encountered the issue.
Logs
No response