build-lib.js 4.4 KB

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