Skip to content

Commit

Permalink
feat: TypeScript REPL (#7)
Browse files Browse the repository at this point in the history
  • Loading branch information
privatenumber authored May 17, 2022
1 parent 6680dce commit 13d5aa6
Show file tree
Hide file tree
Showing 5 changed files with 38 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ Node.js runtime that can instantaneously load TypeScript & ESM, powered by [esbu
### Features
- Transforms TypeScript & ESM → to CJS or ESM (depending on [package type](https://nodejs.org/api/packages.html#type))
- Supports TS extensions `.cjs` & `.mjs` (`.cts` & `.mts`)
- TypeScript REPL
- Supports Node.js v12.20+
- Handles `node:` import prefixes
- Hides experimental feature warnings
Expand Down
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@
"files": [
"dist"
],
"exports": {
"./repl": "./dist/repl.js"
},
"bin": "./dist/cli.js",
"scripts": {
"build": "pkgroll --target=node12.19 --minify",
Expand All @@ -31,6 +34,7 @@
},
"dependencies": {
"@esbuild-kit/cjs-loader": "^2.0.0",
"@esbuild-kit/core-utils": "^1.1.0",
"@esbuild-kit/esm-loader": "^2.0.0"
},
"optionalDependencies": {
Expand Down
2 changes: 2 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ cli({
});
return;
}

// Load REPL
process.argv.push(require.resolve('./repl'));
}

const args = process.argv.slice(2).filter(
Expand Down
28 changes: 28 additions & 0 deletions src/repl.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import repl, { type REPLEval } from 'repl';
import { transform } from '@esbuild-kit/core-utils';
import { version } from '../package.json';

// Copied from
// https://github.com/nodejs/node/blob/v18.2.0/lib/internal/main/repl.js#L37
console.log(
`Welcome to tsx v${version} (Node.js ${process.version}).\n`
+ 'Type ".help" for more information.',
);

const nodeRepl = repl.start();

const { eval: defaultEval } = nodeRepl;

const preEval: REPLEval = async function (code, context, filename, callback) {
const transformed = await transform(code, '.ts').catch(
(error) => {
console.log(error.message);
return { code: '\n' };
},
);

return defaultEval.call(this, transformed.code, context, filename, callback);
};

// @ts-expect-error overriding read-only property
nodeRepl.eval = preEval;

0 comments on commit 13d5aa6

Please sign in to comment.