unplugin-vue-macros npm

Unit Test

English | 简体中文

Extend macros and syntax sugar in Vue.

Features

  • ✨ Extend macros and syntax sugar in Vue.
  • ? Supports both Vue 2 and Vue 3 out-of-the-box.
  • ? Full TypeScript support.
  • ⚡️ Supports Vite, Webpack, Vue CLI, Rollup, esbuild and more, powered by unplugin.

Installation

npm i unplugin-vue-macros -D
Vite
// vite.config.ts import VueMarcos from 'unplugin-vue-macros/vite' import Vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [Vue(), VueMarcos()], })
Rollup
// rollup.config.js import VueMarcos from 'unplugin-vue-macros/rollup' export default { plugins: [VueMarcos()], // Must be before Vue plugin! }
esbuild
// esbuild.config.js import { build } from 'esbuild' build({ plugins: [ require('unplugin-vue-macros/esbuild')(), // Must be before Vue plugin! ], })
Webpack

// webpack.config.js
module.exports = {
  /* ... */
  plugins: [require('unplugin-vue-macros/webpack')()],
}
Vue CLI

// vue.config.js
module.exports = {
  configureWebpack: {
    plugins: [require('unplugin-vue-macros/webpack')()],
  },
}

Usage

defineOptions

Introduce a macro in <script setup>, defineOptions, to use Options API in <script setup>, specifically to be able to set name, props, emits and render in one function.

Note: if you only need defineOptions, the standalone version is better for you.

Basic Usage

<script setup lang="ts">
import { useSlots } from 'vue'
defineOptions({
  name: 'Foo',
  inheritAttrs: false,
})
const slots = useSlots()
</script>
Output
<script lang="ts"> export default { name: 'Foo', inheritAttrs: false, props: { msg: { type: String, default: 'bar' }, }, emits: ['change', 'update'], } </script> <script setup> const slots = useSlots() </script>

JSX in <script setup>

<script setup lang="tsx">
defineOptions({
  render() {
    return <h1>Hello World</h1>
  },
})
</script>
Output

<script lang="tsx">
export default {
  render() {
    return <h1>Hello World</h1>
  },
}
</script>

defineModel

Introduce a macro in <script setup>, defineModel. To be able define and change v-model props as the same as normal variable.

Warning: Reactivity Transform is required. You should enable it first. Otherwise, it will lose the reactivity connection.

Basic Usage

<script setup lang="ts"> let { modelValue } = defineModel<{ modelValue: string }>() console.log(modelValue) modelValue = 'newValue' </script>
Output
<script setup lang="ts"> const { modelValue } = defineProps<{ modelValue: string }>() const emit = defineEmits<{ (evt: 'update:modelValue', value: string): void }>() console.log(modelValue) console.log(emit('update:modelValue', 'newValue')) </script>

TypeScript Support

// tsconfig.json
{
  "compilerOptions": {
    // ...
    "types": ["unplugin-vue-macros" /* ... */]
  }
}

Sponsors

License

MIT License © 2022 三咲智子

GitHub

View Github