get-module-version.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. "use strict"
  2. const path = require("path")
  3. /**
  4. * Gets the module version from package name
  5. */
  6. module.exports = function getModuleVersion(...moduleNames) {
  7. const packageName = moduleNames.pop()
  8. let ownerModuleRootPath = process.cwd()
  9. for (const ownerNames of moduleNames) {
  10. ownerModuleRootPath =
  11. getModuleRootPath(ownerNames, ownerModuleRootPath) ||
  12. ownerModuleRootPath
  13. }
  14. try {
  15. const m = require("module")
  16. const relativeTo = path.join(ownerModuleRootPath, "__placeholder__.js")
  17. // eslint-disable-next-line node/no-unsupported-features/node-builtins -- ignore
  18. return m.createRequire(relativeTo)(`${packageName}/package.json`)
  19. .version
  20. } catch {
  21. // ignore
  22. }
  23. try {
  24. return require(`${packageName}/package.json`).version
  25. } catch {
  26. // ignore
  27. }
  28. return null
  29. }
  30. /**
  31. * Get module root path
  32. */
  33. function getModuleRootPath(packageName, ownerModuleRootPath) {
  34. try {
  35. const m = require("module")
  36. const relativeTo = path.join(ownerModuleRootPath, "__placeholder__.js")
  37. return path.dirname(
  38. // eslint-disable-next-line node/no-unsupported-features/node-builtins -- ignore
  39. m.createRequire(relativeTo).resolve(`${packageName}/package.json`),
  40. )
  41. } catch {
  42. // ignore
  43. }
  44. try {
  45. return path.dirname(require.resolve(`${packageName}/package.json`))
  46. } catch {
  47. // ignore
  48. }
  49. return null
  50. }