Skip to content

Commit

Permalink
Add naive import syntax support
Browse files Browse the repository at this point in the history
Given running esmodules in a node vm to truly evaluate code snippets as
esmodules is still experimental and pretty low level
(https://nodejs.org/docs/latest-v12.x/api/vm.html#vm_class_vm_module)
this hack might work in many cases already.

Demo:

```javascript
console.log(
`
import { v1 as uuidv1 } from 'uuid';
import { v1 } from 'uuid';
import uuid from 'uuid';
import {
  v1 as uuidv1
} from 'uuid';
`
.replace(
  /import\s*\{\s*([^\s]+)\s+as\s+([^\s]+)\s*\}\s*from\s*['"]([^']+)['"]/g,
  'const { $1: $2 } = require("$3")',
)
.replace(
  /import\s*\{\s*([^\s]+)\s*\}\s*from\s*['"]([^']+)['"]/g,
  'const { $1 } = require("$2")',
)
.replace(
  /import\s([^\s]+)\sfrom\s*['"]([^']+)['"]/g,
  'const $1 = require("$2")',
)
);
```

Output:

```
const { v1: uuidv1 } = require("uuid");
const { v1 } = require("uuid");
const uuid = require("uuid");
const { v1: uuidv1 } = require("uuid");
```
  • Loading branch information
ctavan committed Feb 13, 2020
1 parent 7205c1c commit cdeb284
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,20 @@ class Renderer {
line = line.replace(/\s.*/, '');
}
} else if (runArgs && /^```/.test(line)) {
const script = scriptLines.join('\n');
const script = scriptLines
.join('\n')
.replace(
/import\s*\{\s*([^\s]+)\s+as\s+([^\s]+)\s*\}\s*from\s*['"]([^']+)['"]/g,
'const { $1: $2 } = require("$3")',
) // Naive esmodule import support: "import { X as Y } from 'Z'"
.replace(
/import\s*\{\s*([^\s]+)\s*\}\s*from\s*['"]([^']+)['"]/g,
'const { $1 } = require("$2")',
) // Naive esmodule import support: "import { X } from 'Z'"
.replace(
/import\s([^\s]+)\sfrom\s*['"]([^']+)['"]/g,
'const $1 = require("$2")',
); // Naive esmodule import support: "import X from 'Z'"
scriptLines.length = 0;
write('');

Expand Down

0 comments on commit cdeb284

Please sign in to comment.