1.0.0 • Published 8 months ago

@94ai/vite-plugin-vue2 v1.0.0

Weekly downloads
-
License
MIT
Repository
-
Last release
8 months ago

@94ai/vite-plugin-vue2

Note: this plugin only works with Vue@^2.7.0. @vitejs/plugin-vue2 not support config runtime helpers inject modify. @94ai/vite-plugin-vue2 Expanded a configuration normalizerCode to config custom runtime helpers logic.

// vite.config.js, replace @vitejs/plugin-vue2 to @94ai/vite-plugin-vue2
import vue from '@94ai/vite-plugin-vue2'

export default {
  plugins: [vue({
    normalizerCode: `
import { normalizeComponent } from '@94ai/runtime/helpers'
export default normalizeComponent`,
    include: [/\.vue$/, /\.md$/, /\.jsx$/, /\.tsx$/], // other config same with @vitejs/plugin-vue2
    // ...
  })]
}

Options

export interface Options {
  include?: string | RegExp | (string | RegExp)[]
  exclude?: string | RegExp | (string | RegExp)[]

  isProduction?: boolean

  // options to pass on to vue/compiler-sfc
  script?: Partial<Pick<SFCScriptCompileOptions, 'babelParserPlugins'>>
  template?: Partial<
    Pick<
      SFCTemplateCompileOptions,
      | 'compiler'
      | 'compilerOptions'
      | 'preprocessOptions'
      | 'transpileOptions'
      | 'transformAssetUrls'
      | 'transformAssetUrlsOptions'
    >
  >
  style?: Partial<Pick<SFCStyleCompileOptions, 'trim'>>
  /**
   * config custom runtime helpers logic
   */
  normalizerCode?: string;
}

Asset URL handling

When @94ai/vite-plugin-vue2 compiles the <template> blocks in SFCs, it also converts any encountered asset URLs into ESM imports.

For example, the following template snippet:

<img src="../image.png" />

Is the same as:

<script setup>
import _imports_0 from '../image.png'
</script>
<img :src="_imports_0" />

By default the following tag/attribute combinations are transformed, and can be configured using the template.transformAssetUrls option.

{
  video: ['src', 'poster'],
  source: ['src'],
  img: ['src'],
  image: ['xlink:href', 'href'],
  use: ['xlink:href', 'href']
}

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'.

Example for passing options to vue/compiler-sfc:

import vue from '@94ai/vite-plugin-vue2'

export default {
  plugins: [
    vue({
      template: {
        compilerOptions: {
          // ...
        },
        transformAssetUrls: {
          // ...
        }
      }
    })
  ]
}

Example for transforming custom blocks

import vue from '@94ai/vite-plugin-vue2'

const vueI18nPlugin = {
  name: 'vue-i18n',
  transform(code, id) {
    if (!/vue&type=i18n/.test(id)) {
      return
    }
    if (/\.ya?ml$/.test(id)) {
      code = JSON.stringify(require('js-yaml').load(code.trim()))
    }
    return `export default Comp => {
      Comp.i18n = ${code}
    }`
  }
}

export default {
  plugins: [vue(), vueI18nPlugin]
}

License

MIT

1.0.0

8 months ago