Skip to content

Commit

Permalink
fix: 转换JSX语法时,如果是JS匿名函数会导致转换失败
Browse files Browse the repository at this point in the history
  • Loading branch information
gene9831 committed Apr 23, 2024
1 parent 4fd55d4 commit eaa3c57
Showing 1 changed file with 27 additions and 8 deletions.
35 changes: 27 additions & 8 deletions packages/canvas/src/components/render/render.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ const { hyphenateRE } = utils
const customElements = {}

const transformJSX = (code) => {
const res = transformSync(code, {
const opts = {
plugins: [
[
babelPluginJSX,
Expand All @@ -45,13 +45,32 @@ const transformJSX = (code) => {
}
]
]
})
return (res.code || '')
.replace(/import \{.+\} from "vue";/, '')
.replace(/h\(_?resolveComponent\((.*?)\)/g, `h(this.getComponent($1)`)
.replace(/_?resolveComponent/g, 'h')
.replace(/_?createTextVNode\((.*?)\)/g, '$1')
.trim()
}

/**
* @returns {string}
*/
const replaceCode = (code) =>
code
.replace(/import \{.+\} from "vue";/, '')
.replace(/h\(_?resolveComponent\((.*?)\)/g, `h(this.getComponent($1)`)
.replace(/_?resolveComponent/g, 'h')
.replace(/_?createTextVNode\((.*?)\)/g, '$1')
.trim()

try {
const res = transformSync(code, opts)
return replaceCode(res.code || '')
} catch (err) {
// js匿名函数中如果有jsx语法,需要在最外部加上括号才能被正确解析和转换
const res = transformSync(`(${code})`, opts)
const result = replaceCode(res.code || '')
if (result.startsWith('(')) {
const index = result.lastIndexOf(')')
return result.slice(1, index).concat(result.slice(index + 1))
}
return result.trim()
}
}

export const blockSlotDataMap = reactive({})
Expand Down

0 comments on commit eaa3c57

Please sign in to comment.