index.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // noinspection JSUnresolvedReference
  2. import {
  3. addImports,
  4. addServerImports,
  5. createResolver,
  6. defineNuxtModule
  7. } from "@nuxt/kit"
  8. import * as lodash from "lodash-es"
  9. import excludeDefaults from "./exclude.js"
  10. export default defineNuxtModule({
  11. meta: {
  12. // Usually the npm package name of your module
  13. name: "lodash-shared",
  14. // The key in `nuxt.config` that holds your module options
  15. configKey: "lodash",
  16. // Compatibility constraints
  17. compatibility: {
  18. // Semver version of supported nuxt versions
  19. nuxt: "^4.0.0"
  20. }
  21. },
  22. // Default configuration options for your module, can also be a function returning those
  23. defaults: {
  24. // from nuxt-lodash
  25. prefix: "use",
  26. prefixSkip: "is",
  27. exclude: [],
  28. alias: [],
  29. upperAfterPrefix: true
  30. },
  31. // Shorthand sugar to register Nuxt hooks
  32. hooks: {},
  33. // Configuration for other modules - this does not ensure the module runs before
  34. // your module, but it allows you to change the other module's configuration before it runs
  35. moduleDependencies: {},
  36. // The function holding your module logic, it can be asynchronous
  37. setup(options, _nuxt) {
  38. const { resolve } = createResolver(import.meta.url)
  39. const aliasMap = new Map(options.alias)
  40. const excludes = [...options.exclude, ...excludeDefaults]
  41. const prefixSkip = options.prefixSkip
  42. ? lodash.isArray(options.prefixSkip)
  43. ? options.prefixSkip
  44. : [options.prefixSkip]
  45. : []
  46. for (const name of Object.keys(lodash)) {
  47. if (!excludes.includes(name)) {
  48. const alias = aliasMap.has(name) ? aliasMap.get(name) : name
  49. const prefix =
  50. (!prefixSkip.some((key) => alias.startsWith(key)) &&
  51. options.prefix) ||
  52. ""
  53. const as = prefix
  54. ? prefix +
  55. (options.upperAfterPrefix ? lodash.upperFirst(alias) : alias)
  56. : alias
  57. addImports({ name, as, from: resolve("./runtime/lodash") })
  58. addServerImports({ name, as, from: resolve("./runtime/lodash") })
  59. }
  60. }
  61. }
  62. })