If your add-on adds dynamic options via addOption during setup, pass their
types as a type argument:
constaddon=defineAddon<{extra:boolean}>()({...});// Take note of the extra call here: 👆 👆// This works around Typescript's lack of partial type argumentsaddon.options.extra.default;// boolean
}from'sv';exportdefaultdefineAddon(alias)defineAddon<"addon-name",{who:Question<Record<"who",{readonlyquestion:"À qui cet add-on doit-il dire bonjour ?";readonlytype:"string";}>>;}>(config:Addon<{who:Question<Record<"who",{readonlyquestion:"À qui cet add-on doit-il dire bonjour ?";readonlytype:"string";}>>;},"addon-name",Record<string,unknown>>):Addon<{who:Question<Record<"who",{readonlyquestion:"À qui cet add-on doit-il dire bonjour ?";readonlytype:"string";}>>;},"addon-name",Record<string,unknown>>(+1overload)importdefineAddon
If your add-on adds dynamic options via addOption during setup, pass their
types as a type argument:
constaddon=defineAddon<{extra:boolean}>()({...});// Take note of the extra call here: 👆 👆// This works around Typescript's lack of partial type argumentsaddon.options.extra.default;// boolean
:'une meilleure description de ce que fait votre add-on ;)',options(property)options:{who:Question<Record<"who",{readonlyquestion:"À qui cet add-on doit-il dire bonjour ?";readonlytype:"string";}>>;}:defineAddonOptions(alias)defineAddonOptions<never>():OptionBuilder<{},never>importdefineAddonOptions
Options for an addon.
Will be prompted to the user if there are not answered by args when calling the cli.
().add(method)add<"who",Question<Record<"who",{readonlyquestion:"À qui cet add-on doit-il dire bonjour ?";readonlytype:"string";}>>>(key:"who",question:Question<Record<"who",{readonlyquestion:"À qui cet add-on doit-il dire bonjour ?";readonlytype:"string";}>>):OptionBuilder<Record<"who",Question<Record<"who",{readonlyquestion:"À qui cet add-on doit-il dire bonjour ?";readonlytype:"string";}>>>,never>
This type is a bit complex, but in usage, it's quite simple!
The idea is to add() options one by one, with the key and the question.
.add('demo',{question:'Do you want to add a demo?',type:'boolean',// string, number, select, multiselectdefault:true,// condition: (o) => o.previousOption === 'ok',})
('who',{question(property)question:string:'À qui cet add-on doit-il dire bonjour ?',type(property)type:"string":'string'// boolean | number | select | multiselect}).build(method)build():{who:Question<Record<"who",{readonlyquestion:"À qui cet add-on doit-il dire bonjour ?";readonlytype:"string";}>>;}
Required add-ons. Implies runsAfter. Official ids are installed automatically, others must be part of the same run.
('vitest'); // ajoute dynamiquement des options (par ex. basé sur l'état du workspace ou des données récupérées)
// addOption('key', { question: '...', type: 'boolean', default: true });
},run(property)run:(workspace:Workspace&{options:OptionValues<{who:Question<Record<"who",{readonlyquestion:"À qui cet add-on doit-il dire bonjour ?";readonlytype:"string";}>>;}>&Record<string,unknown>;sv:SvApi;cancel:(reason:string)=>void;})=>MaybePromise<void>
Run the addon. The actual execution of the addon... Add files, edit files, etc.
,options(parameter)options:OptionValues<{who:Question<Record<"who",{readonlyquestion:"À qui cet add-on doit-il dire bonjour ?";readonlytype:"string";}>>;}>&Record<string,unknown>
Add-on options (includes dynamically added options from setup)
(({ast(parameter)ast:AST.Root,svelte(parameter)svelte:typeofindex_d_exports$4})=>{svelte(parameter)svelte:typeofindex_d_exports$4.addFragment(alias)index_d_exports$4.addFragment(ast:AST.Root|AST.BaseElement,content:string,options?:{mode?:"append"|"prepend";language?:"ts"|"js";}):voidexportindex_d_exports$4.addFragment(ast(parameter)ast:AST.Root,`<p>Bonjour${options(parameter)options:OptionValues<{who:Question<Record<"who",{readonlyquestion:"À qui cet add-on doit-il dire bonjour ?";readonlytype:"string";}>>;}>&Record<string,unknown>
Add-on options (includes dynamically added options from setup)
.who(property)who:unknown}!</p>`);}));},nextSteps(property)nextSteps?:((workspace:Workspace&{options:OptionValues<{who:Question<Record<"who",{readonlyquestion:"À qui cet add-on doit-il dire bonjour ?";readonlytype:"string";}>>;}>&Record<string,unknown>;})=>string[])|undefined
Next steps to display after the addon is run.
:({options(parameter)options:OptionValues<{who:Question<Record<"who",{readonlyquestion:"À qui cet add-on doit-il dire bonjour ?";readonlytype:"string";}>>;}>&Record<string,unknown>})=>['profitez de cet add-on!']});
Le CLI est divisé en deux paquets avec un frontière claire :
sv = où et quand. Ce paquet gère les paths, la détection de workspace, le suivi de
dépendances, et l’I/O de fichier. Le moteur orchestre l’exécution de l’add-on.
@sveltejs/sv-utils = quoi. Ce paquet fournit des parsers, de l’outillage de
language, et des transformations typées. Tout ici est pur — pas de système de fichiers, pas de
conscience du workspace.
Cette séparation implique que les transformations sont testables sans aucun workspace, et
composables entre add-ons.
Développement
Vous pouvez exécuter votre add-on localement avec le protocole file: :
Ceci vous permet d’itérer rapidement sans publier sur npm.
Le protocole file: fonctionne également pour les add-ons privés ou personnalisés que vous n’avez
pas l’intention de publier — par exemple, pour standardiser la mise en place d’un projet au sein de
votre équipe ou de votre organisation.
Le scipt demo-add compile automatiquement votre add-on avant de l’exécuter.
Tests
Le module sv/testing fournit des utilitaires pour tester votre add-on. createSetupTest est une
usine qui prend vos imports vitest et renvoie une fonction setupTest. Elle crée des vrais projets
SvelteKit à partir de templates, exécute votre add-on, et vous donne accès aux fichiers ainsi
générés.
Returns true if searchString appears as a substring of the result of converting this
object to a String, at one or more positions that are
greater than or equal to position; otherwise, returns false.
searchString
search string
position
If position is undefined, 0 is assumed, so as to search all of the String.
For detailed information, see the documentation of the asynchronous version of
this API: fs.readFile().
If the encoding option is specified then this function returns a
string. Otherwise it returns a buffer.
If buffer is provided and no encoding is specified, the returned {Buffer} is
a view over the supplied buffer containing only the bytes read. If the
supplied buffer is too small to contain the entire file, an error will be
thrown.
Similar to fs.readFile(), when the path is a directory, the behavior of
fs.readFileSync() is platform-specific.
import{readFileSync}from'node:fs';// macOS, Linux, and WindowsreadFileSync('<directory>');// => [Error: EISDIR: illegal operation on a directory, read <directory>]// FreeBSDreadFileSync('<directory>');// => <data>
The right-most parameter is considered {to}. Other parameters are considered an array of {from}.
Starting from leftmost {from} parameter, resolves {to} to an absolute path.
If {to} isn't already absolute, {from} arguments are prepended in right to left order,
until an absolute path is found. If after using all {from} paths still no absolute path is found,
the current working directory is used as well. The resulting path is normalized,
and trailing slashes are removed unless the path gets resolved to the root directory.
paths
A sequence of paths or path segments.
{TypeError} if any of the arguments is not a string.
(cwdconstcwd:string,'src/routes/+page.svelte'),'utf8');expectimportexpect(pageconstpage:string).toContainany('Bonjour tout le monde !');});
Votre fichier vitest.config.js doit contenir la configuration globale de sv/testing :
Le script tests/setup/global.js étant le suivant :
importpath(alias)namespacepathimportpathfrom'node:path';import{setupGlobal(alias)functionsetupGlobal({TEST_DIR,pre,post}:{TEST_DIR:string;pre?:()=>Promise<void>;post?:()=>Promise<void>;}):({provide}:TestProject)=>Promise<()=>Promise<void>>importsetupGlobal}from'sv/testing';// test projects are scaffolded into `<project-root>/.test-output`
constTEST_DIRconstTEST_DIR:string=path(alias)namespacepathimportpath.resolvefunctionpath.resolve(...paths:string[]):string
The right-most parameter is considered {to}. Other parameters are considered an array of {from}.
Starting from leftmost {from} parameter, resolves {to} to an absolute path.
If {to} isn't already absolute, {from} arguments are prepended in right to left order,
until an absolute path is found. If after using all {from} paths still no absolute path is found,
the current working directory is used as well. The resulting path is normalized,
and trailing slashes are removed unless the path gets resolved to the root directory.
paths
A sequence of paths or path segments.
{TypeError} if any of the arguments is not a string.
(import.meta
The type of import.meta.
If you need to declare that a given property exists on import.meta,
this type may be augmented via interface merging.
Les add-on communautaires sont compilés avec tsdown en un seul fichier. Tout
est compilé, à l’exception de sv (qui est une dépendance-paire, fournie lors de l’exécution.)
sv ships its own copy of @sveltejs/sv-utils, so an add-on that leaves it unbundled will still load. Nothing verifies the version: your add-on runs against whatever sv provides, and following its breaking changes is up to you. Bundle it to stay on a version you control.
package.json
Votre add-on doit avoir sv comme dépendance-paire. Les dependencies déclarées ne seront
pas disponibles au moment de l’exécution, tout doit être mis dans le bundle :
package.json :
{"name":"@my-org/sv","version":"1.0.0","type":"module",// point d'entrée compilé (tsdown génère des .mjs pour les ESM)"exports":{".":{"default":"./dist/index.mjs"}},"publishConfig":{"access":"public"},// les paquets déclarés ici ne seront pas disponible à runtime, ils doivent être mis dans le bundle"dependencies":{},"peerDependencies":{// la version minimum requise pour exécuter cet add-on"sv":"^0.13.0"},// Ajoutez le mot-clé "sv-add" afin que les gens puissent trouver votre add-on avec https://www.npmx.dev/search?q=keyword:sv-add"keywords":["sv-add","svelte","sveltekit"]}
Noms de paquets
Le nommage suit les mêmes
restrictions que sur
npm :
prepublishOnly exécute automatiquement le build avant de publier.
Prochaines étapes
Vous pouvez de manière optionnelle afficher des indications à afficher lors de l’exécution de votre
add-on :
import{color(alias)constcolor:{addon:(str:ColorInput)=>string;command:(str:ColorInput)=>string;env:(str:ColorInput)=>string;path:(str:ColorInput)=>string;route:(str:ColorInput)=>string;website:(str:ColorInput)=>string;optional:(str:ColorInput)=>string;dim:(str:ColorInput)=>string;success:(str:ColorInput)=>string;warning:(str:ColorInput)=>string;error:(str:ColorInput)=>string;hidden:(str:ColorInput)=>string;}importcolor}from'@sveltejs/sv-utils';exportdefaultdefineAddonany({ // ...
nextSteps(property)nextSteps:({options}:{options:any;})=>string[]:({options(parameter)options:any})=>[`Lancez${color(alias)constcolor:{addon:(str:ColorInput)=>string;command:(str:ColorInput)=>string;env:(str:ColorInput)=>string;path:(str:ColorInput)=>string;route:(str:ColorInput)=>string;website:(str:ColorInput)=>string;optional:(str:ColorInput)=>string;dim:(str:ColorInput)=>string;success:(str:ColorInput)=>string;warning:(str:ColorInput)=>string;error:(str:ColorInput)=>string;hidden:(str:ColorInput)=>string;}importcolor.command(property)command:(str:ColorInput)=>string('npm run dev')}pour commencer le développement`,`Retrouvez la documentation sur https://...`]});
Compatibilité de version
Votre add-on doit préciser la version minimale de sv requises dans vos peerDependencies. Si la
version de sv d’un utilisateur ou d’un utilisatrice a une majeure différente de celle pour
laquelle votre add-on a été conçu, ils et elles verront un avertissement de compatibilité.