Skip to content

Commit

Permalink
docs: note about SFC submodules convention
Browse files Browse the repository at this point in the history
  • Loading branch information
patak-dev committed Nov 13, 2021
1 parent 2f48e14 commit dd75793
Showing 1 changed file with 11 additions and 7 deletions.
18 changes: 11 additions & 7 deletions docs/guide/api-plugin.md
Expand Up @@ -38,6 +38,9 @@ If your plugin is only going to work for a particular framework, its name should

Vite convention for virtual modules is to prefix the use facing path with `virtual:`. If possible the plugin name should be used as a namespace to avoid collisions with other plugins in the ecosystem. For example, a `vite-plugin-posts` could ask users to import a `virtual:posts` or `virtual:posts/helpers` virtual modules to get build time information. Internally, plugins that use virtual modules should prefix the module ID with `\0` while resolving the id, a convention from the rollup ecosystem. This prevents other plugins from trying to process the id (like node resolution), and core features like sourcemaps can use this info to differentiate between virtual modules and regular files. `\0` is not a permitted char in import URLs so we have to replace them during import analysis. A `\0{id}` virtual id ends up encoded as `/@id/__x00__{id}` during dev in the browser. The id will be decoded back before entering the plugins pipeline, so this is not seen by plugins hooks code.

Note that modules directly derived from a real file, as in the case of a script module in a Single File Component (like a .vue or .svelte SFC) don't need to follow this convention. SFCs generally generate a set of submodules when processed but the code in these can be mapped back to the filesystem. Using `\0` for these submodules would prevent sourcemaps from working correctly.


## Plugins config

Users will add plugins to the project `devDependencies` and configure them using the `plugins` array option.
Expand Down Expand Up @@ -86,28 +89,29 @@ It is common convention to author a Vite/Rollup plugin as a factory function tha

```js
export default function myPlugin() {
const virtualFileId = '@my-virtual-file'
const virtualModuleId = '@my-virtual-module'
const resolvedVirtualModuleId = '\0' + virtualModuleId

return {
name: 'my-plugin', // required, will show up in warnings and errors
resolveId(id) {
if (id === virtualFileId) {
return virtualFileId
if (id === virtualModuleId) {
return resolvedVirtualModuleId
}
},
load(id) {
if (id === virtualFileId) {
return `export const msg = "from virtual file"`
if (id === resolvedVirtualModuleId) {
return `export const msg = "from virtual module"`
}
}
}
}
```

Which allows importing the file in JavaScript:
Which allows importing the module in JavaScript:

```js
import { msg } from '@my-virtual-file'
import { msg } from '@my-virtual-module'

console.log(msg)
```
Expand Down

0 comments on commit dd75793

Please sign in to comment.