fix(nuxt): prevent treeshaking hooks with composable names (#20745)

This commit is contained in:
Daniel Roe 2023-05-09 17:47:46 +01:00 committed by GitHub
parent eb8e9169d6
commit 80d7899f49
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 15 additions and 3 deletions

View File

@ -15,7 +15,10 @@ export const TreeShakeComposablesPlugin = createUnplugin((options: TreeShakeComp
* @todo Use the options import-path to tree-shake composables in a safer way.
*/
const composableNames = Object.values(options.composables).flat()
const COMPOSABLE_RE = new RegExp(`($\\s+)(${composableNames.join('|')})(?=\\()`, 'gm')
const regexp = `(^\\s*)(${composableNames.join('|')})(?=\\((?!\\) \\{))`
const COMPOSABLE_RE = new RegExp(regexp, 'm')
const COMPOSABLE_RE_GLOBAL = new RegExp(regexp, 'gm')
return {
name: 'nuxt:tree-shake-composables:transform',
@ -24,11 +27,11 @@ export const TreeShakeComposablesPlugin = createUnplugin((options: TreeShakeComp
return isVue(id, { type: ['script'] }) || isJS(id)
},
transform (code) {
if (!code.match(COMPOSABLE_RE)) { return }
if (!COMPOSABLE_RE.test(code)) { return }
const s = new MagicString(code)
const strippedCode = stripLiteral(code)
for (const match of strippedCode.matchAll(COMPOSABLE_RE) || []) {
for (const match of strippedCode.matchAll(COMPOSABLE_RE_GLOBAL) || []) {
s.overwrite(match.index!, match.index! + match[0].length, `${match[1]} /*#__PURE__*/ false && ${match[2]}`)
}

View File

@ -1,5 +1,14 @@
import '~/assets/plugin.css'
export class OnMountedMethod {
public onMounted () {
console.log('public onMounted')
}
onBeforeMount () {
console.log('onBeforeMount')
}
}
export default defineNuxtPlugin(() => {
//
})