Commit 303feea

Anton Medvedev <antonmedv@google.com>
2021-08-27 22:37:02
Add cjs support (#203)
1 parent 662fed5
.github/scripts/build.mjs
@@ -0,0 +1,34 @@
+#!/usr/bin/env zx
+
+import path from 'path'
+
+$.verbose = false
+
+let inputFile = path.join(__dirname, '../../index.mjs')
+let outputDir = path.join(path.dirname(inputFile), 'dist')
+
+console.log(chalk.black.bgYellowBright` BUILD `)
+console.log('- inputFile:', inputFile)
+console.log('- outputDir:', outputDir)
+
+let i = 0,
+  spin = () => process.stdout.write(`  ${'⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'[i++ % 10]}\r`),
+  stop = (id => () => clearInterval(id))(setInterval(spin, 100))
+
+let {stdout: bundle} = await $`rollup --format cjs --plugin commonjs,node-resolve ${inputFile}`
+bundle = bundle
+  .replace(/node:(\w+)/g, '$1')
+  .replace(`Object.defineProperty(exports, '__esModule', { value: true });`, ``)
+
+await fs.ensureDir(outputDir)
+await fs.writeFile(path.join(outputDir, 'bundle.cjs'), bundle)
+
+const exportNames = Object.keys(await import(inputFile))
+await fs.writeFile(path.join(outputDir, 'index.cjs'),
+  `const {${exportNames.join(', ')}} = require('./bundle.cjs')
+module.exports = {${exportNames.join(', ')}}
+`)
+
+stop()
+
+console.log(chalk.black.bgGreenBright` DONE `)
.github/workflows/npm-publish.yml
@@ -13,6 +13,7 @@ jobs:
         with:
           node-version: 14
       - run: npm i
+      - run: npm run build
       - run: npm test
       - run: echo "//wombat-dressing-room.appspot.com/:_authToken=$AUTH_TOKEN" >> .npmrc
         env:
.github/workflows/test.yml
@@ -22,4 +22,5 @@ jobs:
       with:
         node-version: ${{ matrix.node-version }}
     - run: npm i
+    - run: npm run build
     - run: npm test
tests/commonjs.cjs
@@ -0,0 +1,5 @@
+let {$} = require('..')
+
+void async function () {
+  await $`echo Hello from CommonJS!`
+}()
.gitignore
@@ -1,4 +1,5 @@
 /node_modules/
 /.idea/
+/dist/
 package-lock.json
 yarn.lock
index.mjs
@@ -99,7 +99,7 @@ if (typeof argv.shell === 'string') {
   $.prefix = ''
 } else {
   try {
-    $.shell = await which('bash')
+    $.shell = which.sync('bash')
     $.prefix = 'set -euo pipefail;'
   } catch (e) {
     $.prefix = '' // Bash not found, no prefix.
package.json
@@ -1,8 +1,12 @@
 {
   "name": "zx",
-  "version": "3.1.0",
+  "version": "4.0.0",
   "description": "A tool for writing better scripts",
-  "main": "index.mjs",
+  "main": "dist/index.cjs",
+  "exports": {
+    "import": "./index.mjs",
+    "require": "./dist/index.cjs"
+  },
   "types": "index.d.ts",
   "bin": {
     "zx": "zx.mjs"
@@ -11,7 +15,8 @@
     "node": ">= 14.8.0"
   },
   "scripts": {
-    "test": "node zx.mjs test.mjs"
+    "test": "node zx.mjs test.mjs",
+    "build": "node zx.mjs .github/scripts/build.mjs"
   },
   "dependencies": {
     "@types/fs-extra": "^9.0.12",
@@ -25,13 +30,18 @@
     "node-fetch": "^2.6.1",
     "which": "^2.0.2"
   },
+  "devDependencies": {
+    "@rollup/plugin-commonjs": "^20.0.0",
+    "@rollup/plugin-node-resolve": "^13.0.4",
+    "rollup": "^2.56.3"
+  },
   "publishConfig": {
     "registry": "https://wombat-dressing-room.appspot.com"
   },
   "files": [
     "*.mjs",
-    "*.js",
-    "*.d.ts"
+    "*.d.ts",
+    "dist"
   ],
   "repository": "google/zx",
   "author": "Anton Medvedev <anton@medv.io>",
test.mjs
@@ -14,7 +14,6 @@
 
 import {strict as assert, deepEqual} from 'assert'
 import path from 'path'
-import {glob} from './index.mjs'
 
 { // Only stdout is used during command substitution
   let hello = await $`echo Error >&2; echo Hello`
@@ -197,6 +196,11 @@ import {glob} from './index.mjs'
   }
 }
 
+{ // CommonJS is working
+  let {stdout} = await $`node tests/commonjs.cjs`
+  assert.match(stdout, /Hello from CommonJS/)
+}
+
 { // require() is working in ESM
   const {name, version} = require('./package.json')
   assert(typeof name === 'string')
zx.mjs
@@ -197,22 +197,13 @@ async function compile(input) {
   $.verbose = false
   let tsc = $`npm_config_yes=true npx -p typescript tsc --target esnext --lib esnext --module esnext --moduleResolution node ${input}`
   $.verbose = v
-
-  let i = 0
-  let interval = setInterval(() => {
-    process.stdout.write('  '
-      + ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'][i++ % 10]
-      + '\r'
-    )
-  }, 100)
-
+  let i= 0, spinner = setInterval(() => process.stdout.write(`  ${'⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'[i++ % 10]}\r`), 100)
   try {
     await tsc
   } catch (err) {
     console.error(err.toString())
   }
-
-  clearInterval(interval)
+  clearInterval(spinner)
   process.stdout.write('   \r')
 }