feat(auto-import): custom include option (#4834)

This commit is contained in:
Anthony Fu 2022-05-06 19:11:34 +08:00 committed by GitHub
parent 2852ec4a2f
commit a862a67c80
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 72 additions and 47 deletions

View File

@ -13,12 +13,18 @@ export const TransformPlugin = createUnplugin(({ ctx, options, sourcemap }: {ctx
const { type, macro } = parseQuery(search)
const exclude = options.transform?.exclude || [/[\\/]node_modules[\\/]/]
const include = options.transform?.include || []
// Exclude node_modules by default
if (exclude.some(pattern => id.match(pattern))) {
return false
}
// Custom includes
if (include.some(pattern => id.match(pattern))) {
return true
}
// vue files
if (
pathname.endsWith('.vue') &&

View File

@ -1,7 +1,7 @@
import { pathToFileURL } from 'node:url'
import { createUnplugin } from 'unplugin'
import { parseQuery, parseURL } from 'ufo'
import { Component } from '@nuxt/schema'
import { Component, ComponentsOptions } from '@nuxt/schema'
import { genDynamicImport, genImport } from 'knitwork'
import MagicString from 'magic-string'
import { pascalCase } from 'scule'
@ -10,12 +10,24 @@ interface LoaderOptions {
getComponents(): Component[]
mode: 'server' | 'client'
sourcemap?: boolean
transform?: ComponentsOptions['transform']
}
export const loaderPlugin = createUnplugin((options: LoaderOptions) => ({
export const loaderPlugin = createUnplugin((options: LoaderOptions) => {
const exclude = options.transform?.exclude || []
const include = options.transform?.include || []
return {
name: 'nuxt:components-loader',
enforce: 'post',
transformInclude (id) {
if (exclude.some(pattern => id.match(pattern))) {
return false
}
if (include.some(pattern => id.match(pattern))) {
return true
}
const { pathname, search } = parseURL(decodeURIComponent(pathToFileURL(id).href))
const query = parseQuery(search)
// we only transform render functions
@ -64,7 +76,8 @@ export const loaderPlugin = createUnplugin((options: LoaderOptions) => ({
}
}
}
}))
}
})
function findComponent (components: Component[], name: string, mode: LoaderOptions['mode']) {
const id = pascalCase(name).replace(/["']/g, '')

View File

@ -105,4 +105,9 @@ export interface ComponentsOptions {
*/
global?: boolean
loader?: boolean
transform?: {
exclude?: RegExp[]
include?: RegExp[]
}
}

View File

@ -5,5 +5,6 @@ export interface AutoImportsOptions extends UnimportOptions {
global?: boolean,
transform?: {
exclude?: RegExp[]
include?: RegExp[]
}
}