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,61 +10,74 @@ interface LoaderOptions {
getComponents(): Component[]
mode: 'server' | 'client'
sourcemap?: boolean
transform?: ComponentsOptions['transform']
}
export const loaderPlugin = createUnplugin((options: LoaderOptions) => ({
name: 'nuxt:components-loader',
enforce: 'post',
transformInclude (id) {
const { pathname, search } = parseURL(decodeURIComponent(pathToFileURL(id).href))
const query = parseQuery(search)
// we only transform render functions
// from `type=template` (in Webpack) and bare `.vue` file (in Vite)
return pathname.endsWith('.vue') && (query.type === 'template' || !!query.macro || !search)
},
transform (code, id) {
const components = options.getComponents()
export const loaderPlugin = createUnplugin((options: LoaderOptions) => {
const exclude = options.transform?.exclude || []
const include = options.transform?.include || []
let num = 0
const imports = new Set<string>()
const map = new Map<Component, string>()
const s = new MagicString(code)
// replace `_resolveComponent("...")` to direct import
s.replace(/(?<=[ (])_?resolveComponent\(["'](lazy-|Lazy)?([^'"]*?)["']\)/g, (full, lazy, name) => {
const component = findComponent(components, name, options.mode)
if (component) {
const identifier = map.get(component) || `__nuxt_component_${num++}`
map.set(component, identifier)
const isClientOnly = component.mode === 'client'
if (isClientOnly) {
imports.add(genImport('#app/components/client-only', [{ name: 'createClientOnly' }]))
}
if (lazy) {
imports.add(genImport('vue', [{ name: 'defineAsyncComponent', as: '__defineAsyncComponent' }]))
imports.add(`const ${identifier}_lazy = __defineAsyncComponent(${genDynamicImport(component.filePath)})`)
return isClientOnly ? `createClientOnly(${identifier}_lazy)` : `${identifier}_lazy`
} else {
imports.add(genImport(component.filePath, [{ name: component.export, as: identifier }]))
return isClientOnly ? `createClientOnly(${identifier})` : identifier
}
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
}
// no matched
return full
})
if (imports.size) {
s.prepend([...imports, ''].join('\n'))
}
const { pathname, search } = parseURL(decodeURIComponent(pathToFileURL(id).href))
const query = parseQuery(search)
// we only transform render functions
// from `type=template` (in Webpack) and bare `.vue` file (in Vite)
return pathname.endsWith('.vue') && (query.type === 'template' || !!query.macro || !search)
},
transform (code, id) {
const components = options.getComponents()
if (s.hasChanged()) {
return {
code: s.toString(),
map: options.sourcemap && s.generateMap({ source: id, includeContent: true })
let num = 0
const imports = new Set<string>()
const map = new Map<Component, string>()
const s = new MagicString(code)
// replace `_resolveComponent("...")` to direct import
s.replace(/(?<=[ (])_?resolveComponent\(["'](lazy-|Lazy)?([^'"]*?)["']\)/g, (full, lazy, name) => {
const component = findComponent(components, name, options.mode)
if (component) {
const identifier = map.get(component) || `__nuxt_component_${num++}`
map.set(component, identifier)
const isClientOnly = component.mode === 'client'
if (isClientOnly) {
imports.add(genImport('#app/components/client-only', [{ name: 'createClientOnly' }]))
}
if (lazy) {
imports.add(genImport('vue', [{ name: 'defineAsyncComponent', as: '__defineAsyncComponent' }]))
imports.add(`const ${identifier}_lazy = __defineAsyncComponent(${genDynamicImport(component.filePath)})`)
return isClientOnly ? `createClientOnly(${identifier}_lazy)` : `${identifier}_lazy`
} else {
imports.add(genImport(component.filePath, [{ name: component.export, as: identifier }]))
return isClientOnly ? `createClientOnly(${identifier})` : identifier
}
}
// no matched
return full
})
if (imports.size) {
s.prepend([...imports, ''].join('\n'))
}
if (s.hasChanged()) {
return {
code: s.toString(),
map: options.sourcemap && s.generateMap({ source: id, includeContent: true })
}
}
}
}
}))
})
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[]
}
}