build-lib.js 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. const babel = require('@babel/core')
  2. const t = require('@babel/types')
  3. const { promisify } = require('node:util')
  4. const glob = promisify(require('glob'))
  5. const fs = require('node:fs')
  6. const path = require('node:path')
  7. const { mkdir, stat, writeFile } = fs.promises
  8. const PACKAGE_JSON_IMPORT = /^\..*\/package.json$/
  9. const SOURCE = 'packages/{*,@uppy/*}/src/**/*.js?(x)'
  10. // Files not to build (such as tests)
  11. const IGNORE = /\.test\.js$|__mocks__|svelte|angular|companion\//
  12. // Files that should trigger a rebuild of everything on change
  13. const META_FILES = [
  14. 'babel.config.js',
  15. 'package.json',
  16. 'package-lock.json',
  17. 'yarn.lock',
  18. 'bin/build-lib.js',
  19. ]
  20. function lastModified (file, createParentDir = false) {
  21. return stat(file).then((s) => s.mtime, async (err) => {
  22. if (err.code === 'ENOENT') {
  23. if (createParentDir) {
  24. await mkdir(path.dirname(file), { recursive: true })
  25. }
  26. return 0
  27. }
  28. throw err
  29. })
  30. }
  31. const moduleTypeCache = new Map()
  32. const versionCache = new Map()
  33. async function isTypeModule (file) {
  34. const packageFolder = file.slice(0, file.indexOf('/src/'))
  35. const cachedValue = moduleTypeCache.get(packageFolder)
  36. if (cachedValue != null) return cachedValue
  37. // eslint-disable-next-line import/no-dynamic-require, global-require
  38. const { type, version } = require(path.join(__dirname, '..', packageFolder, 'package.json'))
  39. const typeModule = type === 'module'
  40. if (process.env.FRESH) {
  41. // in case it hasn't been done before.
  42. await mkdir(path.join(packageFolder, 'lib'), { recursive: true })
  43. }
  44. moduleTypeCache.set(packageFolder, typeModule)
  45. versionCache.set(packageFolder, version)
  46. return typeModule
  47. }
  48. // eslint-disable-next-line no-shadow
  49. function transformJSXImportsToJS (path) {
  50. const { value } = path.node.source
  51. if (value.endsWith('.jsx') && (value.startsWith('./') || value.startsWith('../'))) {
  52. // Rewrite .jsx imports to .js:
  53. path.node.source.value = value.slice(0, -1) // eslint-disable-line no-param-reassign
  54. }
  55. }
  56. async function buildLib () {
  57. const metaMtimes = await Promise.all(META_FILES.map((filename) => lastModified(path.join(__dirname, '..', filename))))
  58. const metaMtime = Math.max(...metaMtimes)
  59. const files = await glob(SOURCE)
  60. /* eslint-disable no-continue */
  61. for (const file of files) {
  62. if (IGNORE.test(file)) {
  63. continue
  64. }
  65. const libFile = file.replace('/src/', '/lib/').replace(/\.jsx$/, '.js')
  66. // on a fresh build, rebuild everything.
  67. if (!process.env.FRESH) {
  68. const [srcMtime, libMtime] = await Promise.all([
  69. lastModified(file),
  70. lastModified(libFile, true),
  71. ])
  72. // Skip files that haven't changed
  73. if (srcMtime < libMtime && metaMtime < libMtime) {
  74. continue
  75. }
  76. }
  77. const plugins = await isTypeModule(file) ? [{
  78. visitor: {
  79. // eslint-disable-next-line no-shadow
  80. ImportDeclaration (path) {
  81. transformJSXImportsToJS(path)
  82. if (PACKAGE_JSON_IMPORT.test(path.node.source.value)
  83. && path.node.specifiers.length === 1
  84. && path.node.specifiers[0].type === 'ImportDefaultSpecifier') {
  85. // Vendor-in version number from package.json files:
  86. const version = versionCache.get(file.slice(0, file.indexOf('/src/')))
  87. if (version != null) {
  88. const [{ local }] = path.node.specifiers
  89. path.replaceWith(
  90. t.variableDeclaration('const', [t.variableDeclarator(local,
  91. t.objectExpression([
  92. t.objectProperty(t.stringLiteral('version'), t.stringLiteral(version)),
  93. ]))]),
  94. )
  95. }
  96. }
  97. },
  98. ExportAllDeclaration: transformJSXImportsToJS,
  99. // eslint-disable-next-line no-shadow
  100. ExportNamedDeclaration (path) {
  101. if (path.node.source != null) {
  102. transformJSXImportsToJS(path)
  103. }
  104. },
  105. },
  106. }] : undefined
  107. const { code, map } = await babel.transformFileAsync(file, { sourceMaps: true, plugins })
  108. const [{ default: chalk }] = await Promise.all([
  109. import('chalk'),
  110. writeFile(libFile, code),
  111. writeFile(`${libFile}.map`, JSON.stringify(map)),
  112. ])
  113. console.log(chalk.green('Compiled lib:'), chalk.magenta(libFile))
  114. }
  115. /* eslint-enable no-continue */
  116. }
  117. console.log('Using Babel version:', require('@babel/core/package.json').version)
  118. buildLib().catch((err) => {
  119. console.error(err)
  120. process.exit(1)
  121. })