Skip to content

Commit

Permalink
feat: add Vite plugin at a given index (#53)
Browse files Browse the repository at this point in the history
  • Loading branch information
Lms24 authored May 6, 2023
1 parent 48be33a commit a76cc20
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/helpers/vite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ export interface AddVitePluginOptions {
* The options of the plugin
*/
options?: Record<string, any>;

/**
* The index in the plugins array where the plugin should be inserted at.
* By default, the plugin is appended to the array.
*/
index?: number;
}

export interface UpdateVitePluginConfigOptions {
Expand All @@ -41,8 +47,12 @@ export function addVitePlugin(
) {
const config = getDefaultExportOptions(magicast);

const insertionIndex = plugin.index ?? config.plugins?.length ?? 0;

config.plugins ||= [];
config.plugins.push(
config.plugins.splice(
insertionIndex,
0,
plugin.options
? builders.functionCall(plugin.constructor, plugin.options)
: builders.functionCall(plugin.constructor)
Expand Down
60 changes: 60 additions & 0 deletions test/helpers/vite.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,64 @@ export default defineConfig({})
});"
`);
});

it("add plugin at index", () => {
const code = `
import { defineConfig } from 'vite'
import { somePlugin1, somePlugin2 } from 'some-module'
export default defineConfig({
plugins: [somePlugin1(), somePlugin2()]
})
`;

const mod = parseModule(code);

addVitePlugin(mod, {
from: "@vitejs/plugin-vue",
constructor: "vuePlugin",
options: {
include: [/\\.vue$/, /\.md$/],
},
index: 0, // at the beginning
});

addVitePlugin(mod, {
from: "vite-plugin-inspect",
constructor: "Inspect",
options: {
build: true,
},
index: 2, // in the middle
});

addVitePlugin(mod, {
from: "vite-plugin-pwa",
imported: "VitePWA",
constructor: "VitePWA",
index: 5, // at the end, out of bounds on purpose
});

expect(generate(mod)).toMatchInlineSnapshot(`
"import { VitePWA } from \\"vite-plugin-pwa\\";
import Inspect from \\"vite-plugin-inspect\\";
import vuePlugin from \\"@vitejs/plugin-vue\\";
import { defineConfig } from \\"vite\\";
import { somePlugin1, somePlugin2 } from \\"some-module\\";
export default defineConfig({
plugins: [
vuePlugin({
include: [/\\\\\\\\.vue$/, /\\\\.md$/],
}),
somePlugin1(),
Inspect({
build: true,
}),
somePlugin2(),
VitePWA(),
],
});"
`);
});
});

0 comments on commit a76cc20

Please sign in to comment.