build-lib.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. const chalk = require('chalk')
  2. const babel = require('@babel/core')
  3. const t = require('@babel/types')
  4. const { promisify } = require('util')
  5. const glob = promisify(require('glob'))
  6. const fs = require('fs')
  7. const path = require('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. if (typeModule) {
  46. await writeFile(path.join(packageFolder, 'lib', 'package.json'), '{"type":"commonjs"}')
  47. }
  48. moduleTypeCache.set(packageFolder, typeModule)
  49. versionCache.set(packageFolder, version)
  50. return typeModule
  51. }
  52. // eslint-disable-next-line no-shadow
  53. function transformExportDeclarations (path) {
  54. const { value } = path.node.source
  55. if (value.endsWith('.jsx') && value.startsWith('./')) {
  56. // Rewrite .jsx imports to .js:
  57. path.node.source.value = value.slice(0, -1) // eslint-disable-line no-param-reassign
  58. }
  59. path.replaceWith(
  60. t.assignmentExpression(
  61. '=',
  62. t.memberExpression(t.identifier('module'), t.identifier('exports')),
  63. t.callExpression(t.identifier('require'), [path.node.source]),
  64. ),
  65. )
  66. }
  67. async function buildLib () {
  68. const metaMtimes = await Promise.all(META_FILES.map((filename) => lastModified(path.join(__dirname, '..', filename))))
  69. const metaMtime = Math.max(...metaMtimes)
  70. const files = await glob(SOURCE)
  71. /* eslint-disable no-continue */
  72. for (const file of files) {
  73. if (IGNORE.test(file)) {
  74. continue
  75. }
  76. const libFile = file.replace('/src/', '/lib/').replace(/\.jsx$/, '.js')
  77. // on a fresh build, rebuild everything.
  78. if (!process.env.FRESH) {
  79. const [srcMtime, libMtime] = await Promise.all([
  80. lastModified(file),
  81. lastModified(libFile, true),
  82. ])
  83. // Skip files that haven't changed
  84. if (srcMtime < libMtime && metaMtime < libMtime) {
  85. continue
  86. }
  87. }
  88. const plugins = await isTypeModule(file) ? [['@babel/plugin-transform-modules-commonjs', {
  89. importInterop: 'none',
  90. }], {
  91. visitor: {
  92. // eslint-disable-next-line no-shadow
  93. ImportDeclaration (path) {
  94. let { value } = path.node.source
  95. if (value.endsWith('.jsx') && value.startsWith('./')) {
  96. // Rewrite .jsx imports to .js:
  97. value = path.node.source.value = value.slice(0, -1) // eslint-disable-line no-param-reassign,no-multi-assign
  98. }
  99. if (PACKAGE_JSON_IMPORT.test(value)
  100. && path.node.specifiers.length === 1
  101. && path.node.specifiers[0].type === 'ImportDefaultSpecifier') {
  102. // Vendor-in version number from package.json files:
  103. const version = versionCache.get(file.slice(0, file.indexOf('/src/')))
  104. if (version != null) {
  105. const [{ local }] = path.node.specifiers
  106. path.replaceWith(
  107. t.variableDeclaration('const', [t.variableDeclarator(local,
  108. t.objectExpression([
  109. t.objectProperty(t.stringLiteral('version'), t.stringLiteral(version)),
  110. ]))]),
  111. )
  112. }
  113. } else if (path.node.specifiers[0].type === 'ImportDefaultSpecifier') {
  114. const [{ local }, ...otherSpecifiers] = path.node.specifiers
  115. if (otherSpecifiers.length === 1 && otherSpecifiers[0].type === 'ImportNamespaceSpecifier') {
  116. // import defaultVal, * as namespaceImport from '@uppy/package'
  117. // is transformed into:
  118. // const defaultVal = require('@uppy/package'); const namespaceImport = defaultVal
  119. path.insertAfter(
  120. t.variableDeclaration('const', [
  121. t.variableDeclarator(
  122. otherSpecifiers[0].local,
  123. local,
  124. ),
  125. ]),
  126. )
  127. } else if (otherSpecifiers.length !== 0) {
  128. // import defaultVal, { exportedVal as importedName, other } from '@uppy/package'
  129. // is transformed into:
  130. // const defaultVal = require('@uppy/package'); const { exportedVal: importedName, other } = defaultVal
  131. path.insertAfter(t.variableDeclaration('const', [t.variableDeclarator(
  132. t.objectPattern(
  133. otherSpecifiers.map(specifier => t.objectProperty(
  134. t.identifier(specifier.imported.name),
  135. specifier.local,
  136. )),
  137. ),
  138. local,
  139. )]))
  140. }
  141. path.replaceWith(
  142. t.variableDeclaration('const', [
  143. t.variableDeclarator(
  144. local,
  145. t.callExpression(t.identifier('require'), [
  146. t.stringLiteral(value),
  147. ]),
  148. ),
  149. ]),
  150. )
  151. }
  152. },
  153. ExportAllDeclaration: transformExportDeclarations,
  154. // eslint-disable-next-line no-shadow,consistent-return
  155. ExportNamedDeclaration (path) {
  156. if (path.node.source != null) return transformExportDeclarations(path)
  157. },
  158. // eslint-disable-next-line no-shadow
  159. ExportDefaultDeclaration (path) {
  160. const moduleExports = t.memberExpression(t.identifier('module'), t.identifier('exports'))
  161. if (!t.isDeclaration(path.node.declaration)) {
  162. path.replaceWith(
  163. t.assignmentExpression('=', moduleExports, path.node.declaration),
  164. )
  165. } else if (path.node.declaration.id != null) {
  166. const { id } = path.node.declaration
  167. path.insertBefore(path.node.declaration)
  168. path.replaceWith(
  169. t.assignmentExpression('=', moduleExports, id),
  170. )
  171. } else {
  172. const id = t.identifier('_default')
  173. path.node.declaration.id = id // eslint-disable-line no-param-reassign
  174. path.insertBefore(path.node.declaration)
  175. path.replaceWith(
  176. t.assignmentExpression('=', moduleExports, id),
  177. )
  178. }
  179. },
  180. },
  181. }] : undefined
  182. const { code, map } = await babel.transformFileAsync(file, { sourceMaps: true, plugins })
  183. await Promise.all([
  184. writeFile(libFile, code),
  185. writeFile(`${libFile}.map`, JSON.stringify(map)),
  186. ])
  187. console.log(chalk.green('Compiled lib:'), chalk.magenta(libFile))
  188. }
  189. /* eslint-enable no-continue */
  190. }
  191. console.log('Using Babel version:', require('@babel/core/package.json').version)
  192. buildLib().catch((err) => {
  193. console.error(err)
  194. process.exit(1)
  195. })