callum
callum

Reputation: 37739

How to use babel's env preset to target Node with ES6 modules enabled?

With this config:

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "node": "16"
        }
      }
    ]
  ]
}

...Babel converts import/export syntax to CommonJS (require).

How do I change this so Babel preserves import and export syntax, so I can run the resulting output as an ES module (e.g. running it with node with an .mjs extension)?

I've tried adding "esmodules": true to the targets, but this doesn't seem to make any difference when combined with "node": "16".

Upvotes: 3

Views: 1849

Answers (1)

samanime
samanime

Reputation: 26547

I just ran into this same issue. The best "solution" I came up with was to simply not use preset-env with the code. Since newer versions of Node basically support all the features that preset-env currently includes, I just didn't apply it, and I'll only apply plugins as needed for experimental solution.

Not a great solution for older versions of Node, but adequate for recent ones.

Upvotes: 0

Related Questions