vitejs / vite-plugin-vue2-jsx

Vite plugin for Vue 2.7 JSX support
MIT License
58 stars 6 forks source link

h function context not same as webpack, which is right? #24

Open defghy opened 8 months ago

defghy commented 8 months ago

use render function to create customElement;

<template>
  <div :style="{ '--node-height': height + 'px' }" class="c-page">
    <VTree ref="vtree" class="constraint-tree" :render="renderNode" :nodeMinHeight="height" />
  </div>
</template>

    renderNode(node: any) {
      let compName = 'CNodeCommon'
      if (isArray) {
        compName = 'CNodeArray'
      }
      return <compName class="contraint-node" info={info} />
    },

webpack use vm.$createElement,context is this image

vite use h function, context is the ui-lib's component image

vite will show this error; Tried jsx in setup or methods both has same problem

 Unknown custom element: <CNodeCommon> - did you register the component correctly?

In my case, webpack is more reasonable, because I cannot controll ui lib's component vue-tree lib: https://github.com/wsfe/vue-tree

"vite": "^5.0.11",
"@vitejs/plugin-vue2": "^2.3.1",
"@vitejs/plugin-vue2-jsx": "^1.1.1",
"vue": "^2.7.16",
defghy commented 8 months ago

I use this solution to temp resolve this problem

renderNode(node: any) {
     const h = this.$createElement  // to replace vite's h
      let compName = 'CNodeCommon'
      if (isArray) {
        compName = 'CNodeArray'
      }
      return <compName class="contraint-node" info={info} />
},
defghy commented 8 months ago

It's @vue/babel-sugar-inject-h which work in webpack; for ObjectMethod|ClassMethod

'ObjectMethod|ClassMethod'(path) {
  if (firstParamIsH(t, path) || !hasJSX(t, path) || isInsideJSXExpression(t, path)) {
    return
  }

  const isRender = path.node.key.name === 'render'

  path
    .get('body')
    .unshiftContainer(
      'body',
      t.variableDeclaration('const', [
        t.variableDeclarator(
          t.identifier('h'),
          isRender
            ? t.memberExpression(t.identifier('arguments'), t.numericLiteral(0), true)
            : t.memberExpression(t.thisExpression(), t.identifier('$createElement')),
        ),
      ]),
    )
},

detail in https://github.com/vuejs/jsx-vue2/blob/2e9f83d5c28bcc95363001fc412db1a659b22e29/packages/babel-sugar-inject-h/src/index.js#L59C25-L59C25

But in vite I use injectH: true option, not work