11import { createFilter } from '@rollup/pluginutils'
22import MagicString from 'magic-string'
33import { findStaticImports , parseStaticImport } from 'mlly'
4+ import { join , resolve } from 'pathe'
45import { type UnpluginOptions } from 'unplugin'
56
6- const ignoredSpecifiers = [ 'vue' , 'vue-router' , 'pinia' ]
7-
8- export function extractLoadersToExport ( code : string ) : string [ ] {
7+ export function extractLoadersToExport (
8+ code : string ,
9+ filterPaths : ( id : string ) => boolean ,
10+ root : string
11+ ) : string [ ] {
912 const imports = findStaticImports ( code )
1013 const importNames = imports . flatMap ( ( i ) => {
1114 const parsed = parseStaticImport ( i )
1215
13- // bail out faster for anything that is not a data loader
14- if (
15- // NOTE: move out to a regexp if the option is exposed
16- parsed . specifier . startsWith ( '@vueuse/' ) &&
17- ignoredSpecifiers . includes ( parsed . specifier )
16+ // since we run post-post, vite will add a leading slash to the specifier
17+ const specifier = resolve (
18+ root ,
19+ parsed . specifier . startsWith ( '/' )
20+ ? parsed . specifier . slice ( 1 )
21+ : parsed . specifier
1822 )
19- return [ ]
23+ console . log ( '🔍' , specifier )
24+
25+ // bail out faster for anything that is not a data loader
26+ if ( ! filterPaths ( specifier ) ) return [ ]
2027
2128 return [
2229 parsed . defaultImport ,
@@ -27,11 +34,17 @@ export function extractLoadersToExport(code: string): string[] {
2734 return importNames
2835}
2936
30- export function createAutoExportPlugin ( ) : UnpluginOptions {
31- const filterVueComponents = createFilter (
32- [ / \. v u e $ / , / \. v u e \? v u e / , / \. v u e \? v = / ]
33- // [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/, /[\\/]\.nuxt[\\/]/]
34- )
37+ export function createAutoExportPlugin ( {
38+ filterPageComponents,
39+ loadersPathsGlobs,
40+ root,
41+ } : {
42+ filterPageComponents : ( id : string ) => boolean
43+ loadersPathsGlobs : string | string [ ]
44+ root : string
45+ } ) : UnpluginOptions {
46+ console . log ( 'Creating auto-export plugin' , loadersPathsGlobs )
47+ const filterPaths = createFilter ( loadersPathsGlobs )
3548
3649 return {
3750 name : 'unplugin-vue-router:data-loaders-auto-export' ,
@@ -40,11 +53,18 @@ export function createAutoExportPlugin(): UnpluginOptions {
4053 transform : {
4154 order : 'post' ,
4255 handler ( code , id ) {
43- if ( ! filterVueComponents ( id ) ) {
56+ // strip query to also match .vue?vue&lang=ts etc
57+ const queryIndex = id . indexOf ( '?' )
58+ const idWithoutQuery = queryIndex >= 0 ? id . slice ( 0 , queryIndex ) : id
59+ if ( ! filterPageComponents ( idWithoutQuery ) ) {
4460 return
4561 }
4662
47- const loadersToExports = extractLoadersToExport ( code )
63+ const loadersToExports = extractLoadersToExport (
64+ code ,
65+ filterPaths ,
66+ root
67+ )
4868
4969 if ( loadersToExports . length <= 0 ) return
5070
0 commit comments