0

I am experimenting with Babel to understand better how it works. I created a simple API with Node.js and TypeScript. Everything works fine when I transpile code and the server runs properly. I have a question though: in node v14.15.3 optional chaining is supported, so why when I build with:

rm -rf build/ && babel src --source-maps --extensions '.js,.ts,.tsx' --ignore '**/*.test.ts' -d build

no matter what version of node I'm running in the shell (by using nvm - v12.18.3 or v14.15.3) the following line

console.log(x?.ciao ?? 10)

it's always transpiled to

console.log((_x$ciao = x === null || x === void 0 ? void 0 : x.ciao) !== null && _x$ciao !== void 0 ? _x$ciao : 10);

I would expect it to use .? and ?? in the transpiled code since they're supported. What am I missing?

I also tried to remove the @babel/preset-typescript preset and did a test with a single file, but yet the code is transpiled as above.

My .babelrc file:

{
  "presets": ["@babel/preset-typescript", ["@babel/preset-env", { "shippedProposals": true }]],
  "plugins": [
    [
      "module-resolver",
      {
        "root": "./src",
        "alias": {
          "@root": ["./"],
          "@src": ["./src"]
        },
        "extensions": [".js", ".ts"]
      }
    ]
  ],
  "sourceMaps": true
}
1
  • 1
    the point of babel is to compile code that works in browsers, it's re-writing the code like that so that it's backwards-compatible Commented Dec 30, 2020 at 5:00

1 Answer 1

0

To make it work use "targets": { "node": 14 } as in the following .babelrc example. This will not transpile .? or ?? since they are supported in node 14.x.

{
  "presets": [
    "@babel/preset-typescript",
    [
      "@babel/preset-env",
      {
        "targets": { "node": 14 }
      }
    ]
  ],
  "plugins": [
    [
      "module-resolver",
      {
        "root": "./src",
        "alias": {
          "@root": ["./"],
          "@src": ["./src"]
        },
        "extensions": [".js", ".ts"]
      }
    ]
  ],
  "sourceMaps": true
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.