Skip to content

feat: add vite-plugin-devtools-json addon #581

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 19 commits into from
Jun 19, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/twelve-shirts-tell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'sv': patch
---

feat: add `devtools-json` addon (using `vite-plugin-devtools-json`)
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ Run package specific tests by specifying a project flag to the package and runni
pnpm test --project core # addons / create / migrate / etc.
```

To run a individual test. `cd` into the package. Run the local `test` script to that package, with a path arg to the individual peice you want tested. Eg:
To run a individual test. `cd` into the package. Run the local `test` script to that package, with a path arg to the individual piece you want tested. Eg:
```bash
pnpm test [path-to-test]
```
Expand Down
1 change: 1 addition & 0 deletions documentation/docs/20-commands/20-sv-add.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,4 @@ You can select multiple space-separated add-ons from [the list below](#Official-
- [`sveltekit-adapter`](sveltekit-adapter)
- [`tailwindcss`](tailwind)
- [`vitest`](vitest)
- [`devtools-json`](devtools-json)
21 changes: 21 additions & 0 deletions documentation/docs/30-add-ons/60-devtools-json.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
title: devtools-json
---

`devtools-json` is essentially a vite plugin [vite-plugin-devtools-json](https://github.com/ChromeDevTools/vite-plugin-devtools-json/) for generating the Chrome DevTools project settings file on-the-fly in the devserver.

It will prevent this server log:

```sh
Not found: /.well-known/appspecific/com.chrome.devtools.json
```

## Usage

```bash
npx sv add devtools-json
```

## What you get

- the `vite` plugin added to your vite plugin options.
4 changes: 3 additions & 1 deletion packages/addons/_config/official.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import type { AddonWithoutExplicitArgs } from '@sveltejs/cli-core';

import devtoolsJson from '../devtools-json/index.ts';
import drizzle from '../drizzle/index.ts';
import eslint from '../eslint/index.ts';
import sveltekitAdapter from '../sveltekit-adapter/index.ts';
import lucia from '../lucia/index.ts';
import mdsvex from '../mdsvex/index.ts';
import paraglide from '../paraglide/index.ts';
import playwright from '../playwright/index.ts';
import prettier from '../prettier/index.ts';
import storybook from '../storybook/index.ts';
import sveltekitAdapter from '../sveltekit-adapter/index.ts';
import tailwindcss from '../tailwindcss/index.ts';
import vitest from '../vitest-addon/index.ts';

Expand All @@ -21,6 +22,7 @@ export const officialAddons = [
playwright,
tailwindcss,
sveltekitAdapter,
devtoolsJson,
drizzle,
lucia,
mdsvex,
Expand Down
50 changes: 50 additions & 0 deletions packages/addons/_tests/devtools-json/test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { expect } from '@playwright/test';
import { setupTest } from '../_setup/suite.ts';
import devtoolsJson from '../../devtools-json/index.ts';
import fs from 'node:fs';
import path from 'node:path';

const { test, variants, prepareServer } = setupTest({ devtoolsJson } as {
devtoolsJson?: typeof devtoolsJson;
});

test.concurrent.for(variants)('default - %s', async (variant, { page, ...ctx }) => {
const cwd = await ctx.run(variant, { devtoolsJson: {} });

const { close } = await prepareServer({ cwd, page });
// kill server process when we're done
ctx.onTestFinished(async () => await close());

const ext = variant.includes('ts') ? 'ts' : 'js';
const viteFile = path.resolve(cwd, `vite.config.${ext}`);
const viteContent = fs.readFileSync(viteFile, 'utf8');

// Check if we have the import part
expect(viteContent).toContain(`import devtoolsJson from`);
expect(viteContent).toContain(`vite-plugin-devtools-json`);

// Check if it's called
expect(viteContent).toContain(`devtoolsJson()`);
});

test.concurrent.for(variants)(
'without selecting the addon specifically - %s',
async (variant, { page, ...ctx }) => {
const cwd = await ctx.run(variant, {});

const { close } = await prepareServer({ cwd, page });
// kill server process when we're done
ctx.onTestFinished(async () => await close());

const ext = variant.includes('ts') ? 'ts' : 'js';
const viteFile = path.resolve(cwd, `vite.config.${ext}`);
const viteContent = fs.readFileSync(viteFile, 'utf8');

// Check if we have the import part
expect(viteContent).toContain(`import devtoolsJson from`);
expect(viteContent).toContain(`vite-plugin-devtools-json`);

// Check if it's called
expect(viteContent).toContain(`devtoolsJson()`);
}
);
40 changes: 40 additions & 0 deletions packages/addons/devtools-json/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { defineAddon } from '@sveltejs/cli-core';
import { array, functions, imports, object, exports } from '@sveltejs/cli-core/js';
import { parseScript } from '@sveltejs/cli-core/parsers';

export default defineAddon({
id: 'devtools-json',
shortDescription: 'devtools json',
homepage: 'https://github.com/ChromeDevTools/vite-plugin-devtools-json',
options: {},

setup: ({ defaultSelection }) => {
defaultSelection({
create: true,
add: false
});
},

run: ({ sv, typescript }) => {
const ext = typescript ? 'ts' : 'js';

sv.devDependency('vite-plugin-devtools-json', '^0.2.0');

// add the vite plugin
sv.file(`vite.config.${ext}`, (content) => {
const { ast, generateCode } = parseScript(content);

const vitePluginName = 'devtoolsJson';
imports.addDefault(ast, 'vite-plugin-devtools-json', vitePluginName);

const { value: rootObject } = exports.defaultExport(ast, functions.call('defineConfig', []));
const param1 = functions.argumentByIndex(rootObject, 0, object.createEmpty());

const pluginsArray = object.property(param1, 'plugins', array.createEmpty());
const pluginFunctionCall = functions.call(vitePluginName, []);
array.push(pluginsArray, pluginFunctionCall);

return generateCode();
});
}
});
15 changes: 11 additions & 4 deletions packages/cli/commands/add/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,15 +201,16 @@ export const add = new Command('add')

common.runCommand(async () => {
const selectedAddonIds = selectedAddons.map(({ id }) => id);
const { nextSteps } = await runAddCommand(options, selectedAddonIds);
if (nextSteps) p.note(nextSteps, 'Next steps', { format: (line) => line });
const { nextSteps } = await runAddCommand(options, selectedAddonIds, 'add');
if (nextSteps) p.note(nextSteps, 'Next steps', { format: (line: string) => line });
});
});

type SelectedAddon = { type: 'official' | 'community'; addon: AddonWithoutExplicitArgs };
export async function runAddCommand(
options: Options,
selectedAddonIds: string[]
selectedAddonIds: string[],
from: 'create' | 'add'
): Promise<{ nextSteps?: string; packageManager?: AgentName | null }> {
const selectedAddons: SelectedAddon[] = selectedAddonIds.map((id) => ({
type: 'official',
Expand Down Expand Up @@ -390,6 +391,11 @@ export async function runAddCommand(
const setups = selectedAddons.length ? selectedAddons.map(({ addon }) => addon) : officialAddons;
const addonSetupResults = setupAddons(setups, workspace);

// get all addons that have been marked to be preselected
const initialValues = Object.entries(addonSetupResults)
.filter(([_, value]) => value.defaultSelection[from] === true)
.map(([key]) => key);

// prompt which addons to apply
if (selectedAddons.length === 0) {
const addonOptions = officialAddons
Expand All @@ -404,7 +410,8 @@ export async function runAddCommand(
const selected = await p.multiselect({
message: `What would you like to add to your project? ${pc.dim('(use arrow keys / space bar)')}`,
options: addonOptions,
required: false
required: false,
initialValues
});
if (p.isCancel(selected)) {
p.cancel('Operation cancelled.');
Expand Down
3 changes: 2 additions & 1 deletion packages/cli/commands/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,8 @@ async function createProject(cwd: ProjectPath, options: Options) {
community: [],
addons: {}
},
[]
[],
'create'
);
packageManager = pm;
addOnNextSteps = nextSteps;
Expand Down
12 changes: 10 additions & 2 deletions packages/cli/lib/install.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,15 +87,23 @@ export function setupAddons(
const addonSetupResults: Record<string, AddonSetupResult> = {};

for (const addon of addons) {
const setupResult: AddonSetupResult = { unsupported: [], dependsOn: [], runsAfter: [] };
const setupResult: AddonSetupResult = {
unsupported: [],
dependsOn: [],
runsAfter: [],
defaultSelection: { create: false, add: false }
};
addon.setup?.({
...workspace,
dependsOn: (name) => {
setupResult.dependsOn.push(name);
setupResult.runsAfter.push(name);
},
unsupported: (reason) => setupResult.unsupported.push(reason),
runsAfter: (name) => setupResult.runsAfter.push(name)
runsAfter: (name) => setupResult.runsAfter.push(name),
defaultSelection: (defaultSelection) => {
setupResult.defaultSelection = defaultSelection;
}
});
addonSetupResults[addon.id] = setupResult;
}
Expand Down
8 changes: 7 additions & 1 deletion packages/core/addon/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export type Addon<Args extends OptionDefinition> = {
dependsOn: (name: string) => void;
unsupported: (reason: string) => void;
runsAfter: (addonName: string) => void;
defaultSelection: (args: { create: boolean; add: boolean }) => void;
}
) => MaybePromise<void>;
run: (workspace: Workspace<Args> & { sv: SvApi }) => MaybePromise<void>;
Expand All @@ -60,7 +61,12 @@ export function defineAddon<Args extends OptionDefinition>(config: Addon<Args>):
return config;
}

export type AddonSetupResult = { dependsOn: string[]; unsupported: string[]; runsAfter: string[] };
export type AddonSetupResult = {
dependsOn: string[];
unsupported: string[];
runsAfter: string[];
defaultSelection: { create: boolean; add: boolean };
};

export type AddonWithoutExplicitArgs = Addon<Record<string, Question>>;
export type AddonConfigWithoutExplicitArgs = Addon<Record<string, Question>>;
Expand Down