提交 ce9272d6 编写于 作者: fxy060608's avatar fxy060608

fix(mp): runtime hooks in setup (#3905)

上级 01ca3b8f
......@@ -5,6 +5,8 @@ import { addLeadingSlash, once, TABBAR_HEIGHT } from '@dcloudio/uni-shared'
import { removeExt, normalizePath } from '../utils'
import { parseJson } from './json'
import { isVueSfcFile } from '../vue/utils'
import { parseVueRequest } from '../vite'
import { EXTNAME_VUE_RE } from '../constants'
const pagesCacheSet: Set<string> = new Set()
......@@ -18,6 +20,16 @@ export function isUniPageFile(
return pagesCacheSet.has(removeExt(file))
}
export function isUniPageSetupAndTs(file: string) {
const { filename, query } = parseVueRequest(file)
return !!(
query.vue &&
query.setup &&
hasOwn(query, 'lang.ts') &&
EXTNAME_VUE_RE.test(filename)
)
}
export function isUniPageSfcFile(
file: string,
inputDir: string = process.env.UNI_INPUT_DIR
......
......@@ -8,6 +8,9 @@ export interface VueQuery {
index?: number
lang?: string
raw?: boolean
setup?: boolean
'lang.ts'?: string
'lang.js'?: string
}
export function parseVueRequest(id: string) {
......
import type { Plugin } from 'vite'
import { MINI_PROGRAM_PAGE_RUNTIME_HOOKS } from '@dcloudio/uni-shared'
import { isUniPageSfcFile } from '@dcloudio/uni-cli-shared'
import { isUniPageSetupAndTs, isUniPageSfcFile } from '@dcloudio/uni-cli-shared'
import { rewriteDefault } from '@vue/compiler-sfc'
type RuntimeHooks = keyof typeof MINI_PROGRAM_PAGE_RUNTIME_HOOKS
......@@ -9,13 +10,17 @@ export function uniRuntimeHooksPlugin(): Plugin {
name: 'uni:mp-runtime-hooks',
enforce: 'post',
async transform(source, id) {
if (!isUniPageSfcFile(id)) {
const isSetupJs = isUniPageSfcFile(id)
const isSetupTs = !isSetupJs && isUniPageSetupAndTs(id)
if (!isSetupJs && !isSetupTs) {
return null
}
if (!source.includes('_sfc_main')) {
if (isSetupJs && !source.includes('_sfc_main')) {
return null
}
if (isSetupTs && !source.includes('defineComponent')) {
return null
}
const matches = source.match(
new RegExp(
`(${Object.keys(MINI_PROGRAM_PAGE_RUNTIME_HOOKS).join('|')})`,
......@@ -33,8 +38,16 @@ export function uniRuntimeHooksPlugin(): Plugin {
for (const hook of hooks) {
flag |= MINI_PROGRAM_PAGE_RUNTIME_HOOKS[hook]
}
if (isSetupJs) {
source = source + `;_sfc_main.__runtimeHooks = ${flag};`
} else if (isSetupTs) {
source =
rewriteDefault(source, '_sfc_defineComponent') +
`\n_sfc_defineComponent.__runtimeHooks = ${flag};\nexport default _sfc_defineComponent`
}
return {
code: source + `;_sfc_main.__runtimeHooks = ${flag};`,
code: source,
map: { mappings: '' },
}
},
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册