How to build with babel and node 14?

Viewed 2969

Im trying to build my project with babel and target node 14.15.4

My .babelrc is like this

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

So i expected babel output will be compatible with current node. Unfortunately babel output keeps using require syntax instead of import so can't be run with node 14, that throws error

require("./server.js");
^

ReferenceError: require is not defined
    at file:///Users/grzegorz/Projects/charts/server/dist/index.js:3:1
    at ModuleJob.run (internal/modules/esm/module_job.js:152:23)
    at async Loader.import (internal/modules/esm/loader.js:166:24)
    at async Object.loadESM (internal/process/esm_loader.js:68:5)

Any idea what im doing wrong?

2 Answers

The following will tell babel not to transform modules:

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

Modules code produced in this manor will contain no inter-op glue. "modules": false is the key to this. Without it babel is very insistent on trans-piling to CommonJS compatible syntax. This option disables all module syntax transforms. This option drops the comp-ability glue and requires usage.

node

Type: string | "current" | true.

If you want to compile against the current node version, you can specify "node": true or "node": "current", which would be the same as "node": process.versions.node.

Example:1

{
  "targets": "current"
}

example:2

{
  "targets": true
}

example:3

{
  "targets": "process.versions.node"
}

Alternatively, you can specify the node version in a browserslist query:

{
  "targets": "node 12" // not recommended
}

Because Node.js may support new language features in minor releases, a program generated for Node.js 12.22 may throw a syntax error on Node.js 12.0. We recommend that you always specify a minor version.

{
  "targets": "node 12.0"
}

Info coming from here!

Related