Write pinia at top level with export syntax. Powered by TS Macro and Unplugin.
pnpm i -D single-pinia
-
TS Macro:
// tsm.config.ts import singlePinia from "single-pinia/ts-macro"; export default { plugins: [ singlePinia() ] };
-
Unplugin, like Vite:
// vite.config.ts import singlePinia from "single-pinia/vite"; import { defineOptions } from "vite"; export default defineOptions({ plugins: [ singlePinia() ] });
Then you can using the following syntax in the file that matches the stores/.*?\.(j|t)sx?
pattern by default:
defineStore("counter");
export const count = ref(0);
export function increment() {
count.value++;
}
export function decrement() {
count.value--;
}
It will be transformed into:
export const useCounterStore = defineStore("counter", () => {
const count = ref(0);
function increment() {
count.value++;
}
function decrement() {
count.value--;
}
return {
count,
increment,
decrement
};
});
This plugin mainly performs the following transformations:
-
Infers the name of the return value from file name.
-
Uses the variables or functions exported under the
defineStore
statement as the setup return values for this store.