2022-04-15 15:19:05 +00:00
|
|
|
import { pathToFileURL } from 'node:url'
|
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-04-22 15:35:42 +00:00
|
|
|
export const TransformPlugin = createUnplugin(({ ctx, options, sourcemap }: {ctx: Unimport, options: Partial<AutoImportsOptions>, sourcemap?: boolean }) => {
|
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) {
|
2022-03-16 13:41:37 +00:00
|
|
|
const { pathname, search } = parseURL(decodeURIComponent(pathToFileURL(id).href))
|
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[\\/]/]
|
2022-05-06 11:11:34 +00:00
|
|
|
const include = options.transform?.include || []
|
2022-03-11 08:09:11 +00:00
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2022-05-06 11:11:34 +00:00
|
|
|
// Custom includes
|
|
|
|
if (include.some(pattern => id.match(pattern))) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2021-08-10 00:27:23 +00:00
|
|
|
// 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) {
|
2022-06-08 20:09:31 +00:00
|
|
|
const { code, s } = await ctx.injectImports(_code, id)
|
2022-03-11 08:09:11 +00:00
|
|
|
if (code === _code) {
|
|
|
|
return
|
2021-08-10 00:27:23 +00:00
|
|
|
}
|
2022-03-11 08:09:11 +00:00
|
|
|
return {
|
|
|
|
code,
|
2022-04-22 15:35:42 +00:00
|
|
|
map: sourcemap && s.generateMap({ source: id, includeContent: true })
|
2021-08-30 11:55:57 +00:00
|
|
|
}
|
2021-08-10 00:27:23 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|