unplugin.mjs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import { promises } from 'node:fs';
  2. import { createFilter } from '@rollup/pluginutils';
  3. import MagicString from 'magic-string';
  4. import { createUnplugin } from 'unplugin';
  5. import { c as createUnimport } from './shared/unimport.2cd87f74.mjs';
  6. import './shared/unimport.1c509f98.mjs';
  7. import 'node:path';
  8. import 'node:process';
  9. import 'pathe';
  10. import 'scule';
  11. import 'mlly';
  12. import 'strip-literal';
  13. import 'node:fs/promises';
  14. import 'node:url';
  15. import 'fast-glob';
  16. import 'picomatch';
  17. import 'node:os';
  18. import 'pkg-types';
  19. import 'local-pkg';
  20. const defaultIncludes = [/\.[jt]sx?$/, /\.vue$/, /\.vue\?vue/, /\.svelte$/];
  21. const defaultExcludes = [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/];
  22. function toArray(x) {
  23. return x == null ? [] : Array.isArray(x) ? x : [x];
  24. }
  25. const unplugin = createUnplugin((options = {}) => {
  26. const ctx = createUnimport(options);
  27. const filter = createFilter(
  28. toArray(options.include || []).length ? options.include : defaultIncludes,
  29. options.exclude || defaultExcludes
  30. );
  31. const dts = options.dts === true ? "unimport.d.ts" : options.dts;
  32. const {
  33. autoImport = true
  34. } = options;
  35. return {
  36. name: "unimport",
  37. enforce: "post",
  38. transformInclude(id) {
  39. return filter(id);
  40. },
  41. async transform(code, id) {
  42. const s = new MagicString(code);
  43. await ctx.injectImports(s, id, {
  44. autoImport
  45. });
  46. if (!s.hasChanged())
  47. return;
  48. return {
  49. code: s.toString(),
  50. map: s.generateMap()
  51. };
  52. },
  53. async buildStart() {
  54. await ctx.init();
  55. if (dts)
  56. return promises.writeFile(dts, await ctx.generateTypeDeclarations(), "utf-8");
  57. }
  58. };
  59. });
  60. export { unplugin as default, defaultExcludes, defaultIncludes };