提交学习笔记专用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

278 lines
7.2 KiB

  1. # @vitejs/plugin-vue [![npm](https://img.shields.io/npm/v/@vitejs/plugin-vue.svg)](https://npmjs.com/package/@vitejs/plugin-vue)
  2. > Note: as of `vue` 3.2.13+ and `@vitejs/plugin-vue` 1.9.0+, `@vue/compiler-sfc` is no longer required as a peer dependency.
  3. ```js
  4. // vite.config.js
  5. import vue from '@vitejs/plugin-vue'
  6. export default {
  7. plugins: [vue()],
  8. }
  9. ```
  10. For JSX / TSX support, [`@vitejs/plugin-vue-jsx`](https://github.com/vitejs/vite-plugin-vue/tree/main/packages/plugin-vue-jsx) is also needed.
  11. ## Options
  12. ```ts
  13. export interface Options {
  14. include?: string | RegExp | (string | RegExp)[]
  15. exclude?: string | RegExp | (string | RegExp)[]
  16. isProduction?: boolean
  17. /**
  18. * Requires @vitejs/plugin-vue@^5.1.0
  19. */
  20. features?: {
  21. /**
  22. * Enable reactive destructure for `defineProps`.
  23. * - Available in Vue 3.4 and later.
  24. * - **default:** `false` in Vue 3.4 (**experimental**), `true` in Vue 3.5+
  25. */
  26. propsDestructure?: boolean
  27. /**
  28. * Transform Vue SFCs into custom elements.
  29. * - `true`: all `*.vue` imports are converted into custom elements
  30. * - `string | RegExp`: matched files are converted into custom elements
  31. * - **default:** /\.ce\.vue$/
  32. */
  33. customElement?: boolean | string | RegExp | (string | RegExp)[]
  34. /**
  35. * Set to `false` to disable Options API support and allow related code in
  36. * Vue core to be dropped via dead-code elimination in production builds,
  37. * resulting in smaller bundles.
  38. * - **default:** `true`
  39. */
  40. optionsAPI?: boolean
  41. /**
  42. * Set to `true` to enable devtools support in production builds.
  43. * Results in slightly larger bundles.
  44. * - **default:** `false`
  45. */
  46. prodDevtools?: boolean
  47. /**
  48. * Set to `true` to enable detailed information for hydration mismatch
  49. * errors in production builds. Results in slightly larger bundles.
  50. * - **default:** `false`
  51. */
  52. prodHydrationMismatchDetails?: boolean
  53. /**
  54. * Customize the component ID generation strategy.
  55. * - `'filepath'`: hash the file path (relative to the project root)
  56. * - `'filepath-source'`: hash the file path and the source code
  57. * - `function`: custom function that takes the file path, source code,
  58. * whether in production mode, and the default hash function as arguments
  59. * - **default:** `'filepath'` in development, `'filepath-source'` in production
  60. */
  61. componentIdGenerator?:
  62. | 'filepath'
  63. | 'filepath-source'
  64. | ((
  65. filepath: string,
  66. source: string,
  67. isProduction: boolean | undefined,
  68. getHash: (text: string) => string,
  69. ) => string)
  70. }
  71. // `script`, `template` and `style` are lower-level compiler options
  72. // to pass on to respective APIs of `vue/compiler-sfc`
  73. script?: Partial<
  74. Omit<
  75. SFCScriptCompileOptions,
  76. | 'id'
  77. | 'isProd'
  78. | 'inlineTemplate'
  79. | 'templateOptions'
  80. | 'sourceMap'
  81. | 'genDefaultAs'
  82. | 'customElement'
  83. >
  84. >
  85. template?: Partial<
  86. Omit<
  87. SFCTemplateCompileOptions,
  88. | 'id'
  89. | 'source'
  90. | 'ast'
  91. | 'filename'
  92. | 'scoped'
  93. | 'slotted'
  94. | 'isProd'
  95. | 'inMap'
  96. | 'ssr'
  97. | 'ssrCssVars'
  98. | 'preprocessLang'
  99. >
  100. >
  101. style?: Partial<
  102. Omit<
  103. SFCStyleCompileOptions,
  104. | 'filename'
  105. | 'id'
  106. | 'isProd'
  107. | 'source'
  108. | 'scoped'
  109. | 'cssDevSourcemap'
  110. | 'postcssOptions'
  111. | 'map'
  112. | 'postcssPlugins'
  113. | 'preprocessCustomRequire'
  114. | 'preprocessLang'
  115. | 'preprocessOptions'
  116. >
  117. >
  118. /**
  119. * Use custom compiler-sfc instance. Can be used to force a specific version.
  120. */
  121. compiler?: typeof _compiler
  122. /**
  123. * @deprecated moved to `features.customElement`.
  124. */
  125. customElements?: boolean | string | RegExp | (string | RegExp)[]
  126. }
  127. ```
  128. ## Asset URL handling
  129. When `@vitejs/plugin-vue` compiles the `<template>` blocks in SFCs, it also converts any encountered asset URLs into ESM imports.
  130. For example, the following template snippet:
  131. ```vue
  132. <img src="../image.png" />
  133. ```
  134. Is the same as:
  135. ```vue
  136. <script setup>
  137. import _imports_0 from '../image.png'
  138. </script>
  139. <img :src="_imports_0" />
  140. ```
  141. By default the following tag/attribute combinations are transformed, and can be configured using the `template.transformAssetUrls` option.
  142. ```js
  143. {
  144. video: ['src', 'poster'],
  145. source: ['src'],
  146. img: ['src'],
  147. image: ['xlink:href', 'href'],
  148. use: ['xlink:href', 'href']
  149. }
  150. ```
  151. Note that only attribute values that are static strings are transformed. Otherwise, you'd need to import the asset manually, e.g. `import imgUrl from '../image.png'`.
  152. ## Example for passing options to `vue/compiler-sfc`:
  153. ```ts
  154. import vue from '@vitejs/plugin-vue'
  155. export default {
  156. plugins: [
  157. vue({
  158. template: {
  159. compilerOptions: {
  160. // ...
  161. },
  162. transformAssetUrls: {
  163. // ...
  164. },
  165. },
  166. }),
  167. ],
  168. }
  169. ```
  170. ## Example for transforming custom blocks
  171. ```ts
  172. import vue from '@vitejs/plugin-vue'
  173. import yaml from 'js-yaml'
  174. const vueI18nPlugin = {
  175. name: 'vue-i18n',
  176. transform(code, id) {
  177. // if .vue file don't have <i18n> block, just return
  178. if (!/vue&type=i18n/.test(id)) {
  179. return
  180. }
  181. // parse yaml
  182. if (/\.ya?ml$/.test(id)) {
  183. code = JSON.stringify(yaml.load(code.trim()))
  184. }
  185. // mount the value on the i18n property of the component instance
  186. return `export default Comp => {
  187. Comp.i18n = ${code}
  188. }`
  189. },
  190. }
  191. export default {
  192. plugins: [vue(), vueI18nPlugin],
  193. }
  194. ```
  195. Create a file named `Demo.vue`, add `lang="yaml"` to the `<i18n>` blocks, then you can use the syntax of `YAML`:
  196. ```vue
  197. <template>Hello</template>
  198. <i18n lang="yaml">
  199. message: 'world'
  200. fullWord: 'hello world'
  201. </i18n>
  202. ```
  203. `message` is mounted on the i18n property of the component instance, you can use like this:
  204. ```vue
  205. <script setup lang="ts">
  206. import Demo from 'components/Demo.vue'
  207. </script>
  208. <template>
  209. <Demo /> {{ Demo.i18n.message }}
  210. <div>{{ Demo.i18n.fullWord }}</div>
  211. </template>
  212. ```
  213. ## Using Vue SFCs as Custom Elements
  214. > Requires `vue@^3.2.0` & `@vitejs/plugin-vue@^1.4.0`
  215. Vue 3.2 introduces the `defineCustomElement` method, which works with SFCs. By default, `<style>` tags inside SFCs are extracted and merged into CSS files during build. However when shipping a library of custom elements, it may be desirable to inline the styles as JavaScript strings and inject them into the custom elements' shadow root instead.
  216. Starting in 1.4.0, files ending with `*.ce.vue` will be compiled in "custom elements" mode: its `<style>` tags are compiled into inlined CSS strings and attached to the component as its `styles` property:
  217. ```js
  218. import { defineCustomElement } from 'vue'
  219. import Example from './Example.ce.vue'
  220. console.log(Example.styles) // ['/* css content */']
  221. // register
  222. customElements.define('my-example', defineCustomElement(Example))
  223. ```
  224. Note in custom elements mode there is no need to use `<style scoped>` since the CSS is already scoped inside the shadow DOM.
  225. The `customElement` plugin option can be used to configure the behavior:
  226. - `{ customElement: true }` will import all `*.vue` files in custom element mode.
  227. - Use a string or regex pattern to change how files should be loaded as Custom Elements (this check is applied after `include` and `exclude` matches).
  228. ## License
  229. MIT