npm | github | vuedc playground
Vue Declassified is an opinionated tool that will format Vue class components (including the v8 RC package) to script setup. This project a fork and re-write of yoyo930021's vc2c which is focused more on Vue 2 -> Composition API using defineComponent
.
These decisions are made arbitrarily, mostly for sanity and convenience. You get what you get and you don't get upset.
- Limited configuration
- There is a lot of different edge cases to test and adding configuration options tends to act as a multiplier for those cases.
- Will only support TS
- Won't support esoteric/redundant
@Component
/@Options
options- Will consider accepting PRs
- Will order files
script
->template
->style
- Will reference macros by arbitrary variables (see below)
- Will be formatted by prettier with default config
- exception
printWidth
increased to 100 characters
- exception
- Mixins will be renamed to match composable conventions (see Tips/Gotchas: Mixins)
- When transforming TypeScript files containing mixins a new composable will be appended to the file but the existing mixin will be left
You can call the CLI tool to convert a file directly from a terminal. For more information see the vuedc readme.
pnpm add -g @heatsrc/vuedc
# or
npm install -g @heatsrc/vuedc
# or
yarn add -g @heatsrc/vuedc
vuedc -i myVueComponent.vue -o myVueComponent.converted.vue
# Or create composables out of VCC Mixins
vuedc -i myMixin.ts
or run directly with hot loading
pnpm dlx @heatsrc/vuedc -i myVueComponent.vue -o myVueComponent.converted.vue
# or
npx @heatsrc/vuedc -i myVueComponent.vue -o myVueComponent.converted.vue
# or
yarn dlx @heatsrcvuedc -i myVueComponent.vue -o myVueComponent.converted.vue
If you want to use this without the cli tool you'll need to ensure you have the following packages installed
- typescript@^5.2.2
- vue@^3.3.4
- prettier@^3.0.3
Additionally vue-declassified requires Node 18+
pnpm add @heatsrc/vue-declassified
# or
npm install @heatsrc/vue-declassified
# or
yarn install @heatsrc/vue-declassified
Vuedc provides a very limited set of options to keep maintainability of the program sustainable.
export type VuedcOptions = {
/**
* When true Vuedc will not stringify the vue file but instead return the
* variable collisions
*/
stopOnCollisions?: boolean;
/**
* When provided Vuedc will attempt to find a tsconfig.json project file along
* the path. If found it will use the compiler options from this file rather
* than simple defaults.
*
* Note: Unless you need external file references (e.g., mixins), it's
* recommended not providing this. Using your project can be *significantly*
* slower as TS will need to compile your entire project and uses the file
* system rather than an in-memory file system when no project is provided.
*/
basePath?: string;
};
import { convertSfc, convertMixin } from "@heatsrc/vue-declassified";
import {readFile, writeFile} from 'node:fs/promises';
import { dirname, extName } from 'node:path';
const input = "./myVueComponent.vue";
const output = "./myVueComponent.converted.vue";
(async () => {
const encoding = {encoding: 'utf8'};
const ext = extName(input);
const inputFile = await readFile(input, encoding);
const result: string | undefined;
if (extName === '.vue') {
result = await convertSfc(input);
// or with options
// result = await convertSfc(input, {stopOnCollisions: true, basePath: dirname(input)});
} else {
result = await convertMixin(input);
// or with options
// result = await convertMixin(input, {stopOnCollisions: true, basePath: dirname(input)});
}
await writeFile(output, encoding);
}());
import { convertScript } from "@heatsrc/vue-declassified";
const input = `
import { Component } from 'vue-class-component';
@Component()
export default class MyComponent extends Vue {
myData: string = 'foo';
}`;
const result = convertScript(input);
console.log(result);
// import { ref } from 'vue';
// const myData = ref<string>('foo');
Legend | |
---|---|
β | Currently supported |
βοΈ | Not currently being supported but being worked on |
π€ | Support is not prioritized |
π₯ | No transform path to script setup (breaking change in Vue 2 -> 3) |
π | All planned features are supported in section, let go! |
Basic class transforms (6 β / 1 βοΈ)
feature | supported? | notes |
---|---|---|
methods | β | Basic method support (no decorators) |
data properties | β | Basic class properties (no decorators) |
getters/setters | β | Computed refs |
mixins | β | βRequires basePath option to be set (see Tips/Gotchas: Mixins) |
extend | βοΈ | |
sort by dependency | β | Will try to sort dependencies* |
$refs:! {...} |
β | converted to regular Ref s |
* VueDc does it best to sort dependencies to avoid "used before defined" issues. It requires processing essentially a directed acyclic graph and it's complicated so please raise issues if found.
Lifecycle Hooks (11/11 π)
lifecycle hooks | supported? | notes |
---|---|---|
beforeCreate | β | body contents moved to root of script setup body |
created | β | body contents moved to root of script setup body |
beforeMount | β | onBeforeMount |
mounted | β | onMounted |
beforeUpdate | β | onBeforeUpdate |
updated | β | onUpdated |
activated | β | onActivated |
deactivated | β | onDeactivated |
beforeDestroy | β | onBeforeDestroy |
destroyed | β | onDestroy |
errorCaptured | β | onErrorCaptured |
this.
(11 β
/ 3 βοΈ / 5 π₯)
this. |
supported? | notes |
---|---|---|
PropertyAccess | β | Primitives: Ref , Complex: Reactive , Uninitialized: Regular variables |
methods | β | |
$attrs |
βοΈ | Via const attrs = useAttrs() |
$data |
β | Treated same as data Class PropertyAssignments |
$emit |
β | Via const emit = defineEmits<...>() |
$nextTick |
β | Via import { nextTick } from 'vue'; |
$parent |
π₯ | Refactor your code. Prop/Emits or Provide/Inject* |
$children |
π₯ | - |
$props |
β | Via const props = defineProps<...>() |
$refs |
β | Converted to standard `Ref |
$route |
β | Via const route = useRoute(); |
$router |
β | Via const router = useRouter(); |
$slots |
βοΈ | Via const slots = defineSlots<...>() |
$scopedSlots |
βοΈ | Via const slots = defineSlots<...>() |
$store |
β | Via const store = useStore(); |
$watch |
β | Via import { watch } from 'vue'; |
$on |
π₯ | |
$once |
π₯ | |
$off |
π₯ |
These are options provided in the decorator call, e.g., @Component({ components: { MyIcon } })
. All Options API fields are technically supported in Vue Class Components (e.g., data, computed, methods, etc) but many of them don't make sense and will not be actively developed but PRs may be accepted.
Options-Data (4/4 π)
Options-Data | supported? | notes |
---|---|---|
data | π€ | While you can add these what you even using VCC for? |
props | β | |
propsData | π€ | This is primarily a testing feature |
computed | π€ | While you can add these what you even using VCC for? |
watch | β | |
exposes | β | RC Feature since Vue 3 require declaring exposed fields |
emits | β | RC Feature since Vue 3 require declaring events that are emitted |
Options-Assets (2 βοΈ / 1 π€)
Options-Assets | supported? | notes |
---|---|---|
directives | βοΈ | Will attempt to rename directives if they don't match |
filters | βοΈ | Will be converted to simple methods, you'll need to fix pipe style filters in your html templates |
components | π€ | If you chance the name of your imports this may break |
Options-Composition (1 βοΈ / 3 π€)
Options-Composition | supported? | notes |
---|---|---|
parent | π€ | Seem hacky to be specifying a parent in VCC SFC |
mixins | π€ | While you can add these what are you even using VCC for? |
extends | π€ | - |
provide/inject | βοΈ |
Options-Misc (2 βοΈ / 4 π€)
Options-Misc | supported? | notes |
---|---|---|
name | π€ | Doesn't make much sense an script setup |
delimiters | π€ | |
functional | π€ | If all it uses is props script setup will automatically be functional |
model | βοΈ | |
inheritAttrs | βοΈ | |
comments | π€ | VueDc will try to preserve comments by default |
Options-DOM (4/4 π€)
Options-DOM | supported? | notes |
---|---|---|
el | π€ | DOM Options are more suited for Options API |
template | π€ | - |
render | π€ | - |
renderError | π€ | - |
Options-LifeCycleHooks (11/11 π€)
Options-LifeCycle Hooks | supported? | notes |
---|---|---|
beforeCreate | π€ | While you can add these what you even using VCC for? |
created | π€ | - |
beforeMount | π€ | - |
mounted | π€ | - |
beforeUpdate | π€ | - |
updated | π€ | - |
activated | π€ | - |
deactivated | π€ | - |
beforeDestroy | π€ | - |
destroyed | π€ | - |
errorCaptured | π€ | - |
Decorators
(6 β
1 βοΈ / 3 π€)
decorator | supported? | notes |
---|---|---|
@Prop |
β | |
@PropSync |
π€ | |
@Model |
βοΈ | |
@Watch |
β | |
@Provide |
β | |
@Inject |
β | |
@ProvideReactive |
π€ | |
@InjectReactive |
π€ | |
@Emit |
β | |
@Ref |
β | Currently parsing templates isn't in the works so ref aliases will require updating if used. |
Decorators
(5/5 π)
decorator | supported? | notes |
---|---|---|
@Action |
β | |
@Getter |
β | |
@Mutation |
β | |
@State |
β | |
namespace | β |
Other features (7/7 π)
- β
Limited type inference
- If a node is untyped, will do a best guess at type (mostly primitive types only).
- When encountering
$emit
s will try to infer parameter names/types. - Fails back to
unknown
keyword if it's not certain.
- β
Sorting by dependencies
- Will sort statements so definitions occur before uses.
- β
Merging macros/props/etc
- If you're code is doing insane stuff like defining props in both the
@Component
options and as decorators,@Props
/@Emit
/ etc, vuedc will merge the definitions.
- If you're code is doing insane stuff like defining props in both the
- β
Naming collision detection
- Will detect collisions from imports, variable declarations and instance properties that have been converted to top level (e.g.,
$ref.button
=>button.value
).
- Will detect collisions from imports, variable declarations and instance properties that have been converted to top level (e.g.,
- β
Automatic macro definitions
- Props ->
defineProps
(also will addwithDefaults
if vuedc detects defaults). - Emit ->
defineEmits
.
- Props ->
- β
Composable definitions
- When former "builtin" globals such as
$store
/$router
/etc are found vuedc will automatically import and assign to a variable - e.g.,
const store = useStore()
- When former "builtin" globals such as
- β
Transforming Mixin
- Typescript files can be provided to
convertMixin
and any mixin found in that file will have a composable analogue created and appended to the file.
- Typescript files can be provided to
Vue expects directive and components to match their name (PascalCase
/camelCase
-> kebab-case
).
Currently Vuedc doesn't detect if you've used a different name and aliased it in the component options
<script lang="ts">
import {Component, Vue} from 'vue-class-components';
import myComponentVue from './MyComponent.vue';
import myDirective from './MyDirective.ts';
@Component({
components: { MyComponent: myComponentVue },
directives: { vMyDirective: myDirective }
})
export default Foo extends Vue {}
</script>
// will be converted to:
<script setup lang="ts">
import myComponentVue from "./MyComponent.vue";
import myDirective from "./MyDirective.ts";
</script>
<template>
<!-- This is a problem ! -->
<my-component v-my-directive />
</template>
So make sure to rename your imports to match what the template is calling.
e.g.,
<script setup lang="ts">
import MyComponent from "./MyComponent.vue";
import vMyDirective from "./vMyDirective.ts";
</script>
<template>
<my-component v-my-directive />
</template>
It's strongly recommended you resolve potential naming collisions prior to converting your code, vuedc doesn't have complete knowledge of the codes intention and doesn't update templates (yet?) so it can't reliably rename variables for you.
Common reasons for naming collisions:
Properties on the $refs
object get converted to top level variable declarations and can collide with other class members sharing the same name.
e.g.,
@Component
export default class Foo extends Vue {
foo = "bar";
$refs!: {
foo: HTMLDivElement;
};
}
// will be converted to
const foo = ref<string>("bar");
const foo = ref<HTMLDivElement>();
// ^? Cannot redeclare block-scoped variable 'foo'.ts(2451)
It's not uncommon for you to import a variable from another module and make it available as a class member with the same name.
e.g.,
import foo from './foo';
const bar = foo;
const { a, b: { c } } = {a: true, b: { c: false } };
const [d, e, {f}] = [1, 2, {f: 3}];
@Component
export default Foo {
foo = 'string';
a = 1;
b = 'b';
d = [1, 2, 3];
@Inject e: () => 'e';
@Action f: () => Promise<void>;
get bar() {
}
c() {
}
}
// will be converted to
import foo from './foo';
const bar = foo;
const { a, b: { c } } = {a: true, b: { c: false } };
const [d, e, {f}] = [1, 2, {f: 3}];
const foo = ref('string');
// ^? Cannot redeclare block-scoped variable 'foo'.ts(2451)
const a = ref(1);
// ^? Cannot redeclare block-scoped variable 'a'.ts(2451)
const b = ref('b');
// ^? Cannot redeclare block-scoped variable 'b'.ts(2451)
const d = reactive([1, 2, 3]);
// ^? Cannot redeclare block-scoped variable 'd'.ts(2451)
const e = inject<() => 'e'>('e');
// ^? Cannot redeclare block-scoped variable 'e'.ts(2451)
const f = (): Promise<void> => store.dispatch('f');
// ^? Cannot redeclare block-scoped variable 'f'.ts(2451)
const bar = computed(() => 'val');
// ^? Cannot redeclare block-scoped variable 'bar'.ts(2451)
const c = () => 'foo';
// ^? Cannot redeclare block-scoped variable 'c'.ts(2451)
When Vuedc encounters a data property assigned to an Array or Object it will assume you want to wrap it in reactive
. This can be a problem if you're reassigning the variable in the code. Vuedc will assign the variable to a const
so it should be immediately apparently that something is wrong and it's up to you how to refactor it.
You can convert the reactive
to ref
and add .value
to the reassignments but you will lose deep reactivity of those variables (which may be the intention.)
β Note: Mixins support only works when you provide convertSfc
with a basePath
in the VuedcOptions (or with the -p | --project
flag in the Vuedc cli tool).
When mixins are detected Vuedc will assume you've created a composable analog in the same file and perform the following
- Transform
- First char of mixin will be capitalized: (
fooMixin
->FooMixin
) use
will be prefixed: (FooMixin
->useFooMixin
)Mixin
will be removed (if detected): (useFooMixin
->useFoo
)
- First char of mixin will be capitalized: (
- Exported variables are mapped 1:1 with public members of Mixin
- e.g.,
const { isLoading, bar, fetchData } = useFoo();
- e.g.,
- All public members belonging to the mixin will be imported by the component
- Property/Accessors will have
.value
added to the property access- e.g.,
const isReady = computed(() => !isLoading.value)
- e.g.,
βΉοΈ Vuedc cannot (yet) detect which mixin members have been used in the template so will just import them all and you should refactor to remove unused variables.
βΉοΈ The old mixin isn't deleted from the import so it's up to you to clean it up.