2021-08-10 00:27:23 +00:00
|
|
|
import { createUnplugin } from 'unplugin'
|
|
|
|
import { parseQuery, parseURL } from 'ufo'
|
2022-03-11 08:09:11 +00:00
|
|
|
import { Unimport } from 'unimport'
|
|
|
|
import { AutoImportsOptions } from '@nuxt/schema'
|
2021-08-10 00:27:23 +00:00
|
|
|
|
2022-03-11 08:09:11 +00:00
|
|
|
export const TransformPlugin = createUnplugin(({ ctx, options }: {ctx: Unimport, options: Partial<AutoImportsOptions> }) => {
|
2021-08-10 00:27:23 +00:00
|
|
|
return {
|
2022-02-10 09:29:49 +00:00
|
|
|
name: 'nuxt:auto-imports-transform',
|
2021-08-10 00:27:23 +00:00
|
|
|
enforce: 'post',
|
|
|
|
transformInclude (id) {
|
|
|
|
const { pathname, search } = parseURL(id)
|
2022-01-17 18:27:23 +00:00
|
|
|
const { type, macro } = parseQuery(search)
|
2021-08-10 00:27:23 +00:00
|
|
|
|
2022-03-11 08:09:11 +00:00
|
|
|
const exclude = options.transform?.exclude || [/[\\/]node_modules[\\/]/]
|
|
|
|
|
2021-12-21 14:28:45 +00:00
|
|
|
// Exclude node_modules by default
|
2022-03-11 08:09:11 +00:00
|
|
|
if (exclude.some(pattern => id.match(pattern))) {
|
2021-08-10 00:27:23 +00:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// vue files
|
2021-10-13 20:24:13 +00:00
|
|
|
if (
|
|
|
|
pathname.endsWith('.vue') &&
|
2022-01-17 18:27:23 +00:00
|
|
|
(type === 'template' || type === 'script' || macro || !search)
|
2021-10-13 20:24:13 +00:00
|
|
|
) {
|
2021-08-10 00:27:23 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
// js files
|
2021-10-13 21:03:36 +00:00
|
|
|
if (pathname.match(/\.((c|m)?j|t)sx?$/g)) {
|
2021-08-10 00:27:23 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
},
|
2022-03-11 08:09:11 +00:00
|
|
|
async transform (_code, id) {
|
|
|
|
const { code, s } = await ctx.injectImports(_code)
|
|
|
|
if (code === _code) {
|
|
|
|
return
|
2021-08-10 00:27:23 +00:00
|
|
|
}
|
2022-03-11 08:09:11 +00:00
|
|
|
return {
|
|
|
|
code,
|
|
|
|
map: s.generateMap({ source: id, includeContent: true })
|
2021-08-30 11:55:57 +00:00
|
|
|
}
|
2021-08-10 00:27:23 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|