benjamn / benjamn/recast

ES Module import in node

Open
#625 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
TypeScript
Stars
5.3k
Forks
363
Avg merge
3d 8h
Merged PRs (30d)
3

Description

I'm trying to support native ES modules in node 12 through the `--experimental-modules` flag, coming from the [`esm`](https://github.com/standard-things/esm) package.

But with recast, I had a strange issue.

When importing it with the esm package, I have to import it as `import {* as recast} from 'recast'`. So recast makes itself available as separate, non-default exports, that can be grouped using the `*`-syntax.

When importing recast with the node flag, I have to import it as `import recast from 'recast'`. So recast seems to export a default, bundling all functions.

The only way around it (without patching recast) is to check after the import whether it has a default export or not, and then use the correct one.
```js
import * as _recast from 'recast'
const recast = ('default' in _recast) ? _recast.default : _recast
```

When checking the recast code, I saw the following line in the generated `main.js`:
```js
Object.defineProperty(exports, "__esModule", { value: true });
```
I have no idea what it does, but apparently it's something from typescript that tries to enable ES modules, and thus confuses the `esm` package or node. Commenting out this line out also fixed my issue.

I have no idea if it should be considered an issue with the recast code, with TypeScript, with the esm package or with node module handling. But it's definitely an annoying difference.

Contributor guide

No contributing guide indexed for this repository

Research direction

Reproduce the differing imports with Node 12's --experimental-modules flag and the esm package. Inspect the generated main.js, especially the Object.defineProperty(exports, "__esModule", { value: true }) line, and compare the resulting export shapes. Done means recast exposes a consistent import interface in both reported environments.

Written by the indexing model from the issue text.

Assessment

Tech stack
node.js, typescript
Domain
build-system, tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.