Kaynağa Gözat

meta: fix support of export declaration in source files (#3558)

Rewrite all `export … from …` to `module.exports = require(…)`, and
`export default …` to `module.exports = …`  when transpiling ESM to CJS.

It also transform `.jsx` imports into `.js` as we are not shipping JSX to npm.
Antoine du Hamel 3 yıl önce
ebeveyn
işleme
6012220d17
1 değiştirilmiş dosya ile 44 ekleme ve 0 silme
  1. 44 0
      bin/build-lib.js

+ 44 - 0
bin/build-lib.js

@@ -56,6 +56,23 @@ async function isTypeModule (file) {
   return typeModule
 }
 
+// eslint-disable-next-line no-shadow
+function transformExportDeclarations (path) {
+  const { value } = path.node.source
+  if (value.endsWith('.jsx') && value.startsWith('./')) {
+    // Rewrite .jsx imports to .js:
+    path.node.source.value = value.slice(0, -1) // eslint-disable-line no-param-reassign
+  }
+
+  path.replaceWith(
+    t.assignmentExpression(
+      '=',
+      t.memberExpression(t.identifier('module'), t.identifier('exports')),
+      t.callExpression(t.identifier('require'), [path.node.source]),
+    ),
+  )
+}
+
 async function buildLib () {
   const metaMtimes = await Promise.all(META_FILES.map((filename) => lastModified(path.join(__dirname, '..', filename))))
   const metaMtime = Math.max(...metaMtimes)
@@ -122,6 +139,33 @@ async function buildLib () {
             )
           }
         },
+        ExportAllDeclaration: transformExportDeclarations,
+        // eslint-disable-next-line no-shadow,consistent-return
+        ExportNamedDeclaration (path) {
+          if (path.node.source != null) return transformExportDeclarations(path)
+        },
+        // eslint-disable-next-line no-shadow
+        ExportDefaultDeclaration (path) {
+          const moduleExports =  t.memberExpression(t.identifier('module'), t.identifier('exports'))
+          if (!t.isDeclaration(path.node.declaration)) {
+            path.replaceWith(
+              t.assignmentExpression('=', moduleExports, path.node.declaration),
+            )
+          } else if (path.node.declaration.id != null) {
+            const { id } = path.node.declaration
+            path.insertBefore(path.node.declaration)
+            path.replaceWith(
+              t.assignmentExpression('=', moduleExports, id),
+            )
+          } else {
+            const id = t.identifier('_default')
+            path.node.declaration.id = id // eslint-disable-line no-param-reassign
+            path.insertBefore(path.node.declaration)
+            path.replaceWith(
+              t.assignmentExpression('=', moduleExports, id),
+            )
+          }
+        },
       },
     }] : undefined
     const { code, map } = await babel.transformFileAsync(file, { sourceMaps: true, plugins })