可选链在create-react-app中不起作用

时间:2020-04-26 11:47:48

标签: javascript reactjs babeljs react-scripts

在一个create-react-app项目中,我在自己的.babelrc中使用@babel/plugin-proposal-optional-chaining

但是,我遇到此错误:Module parse failed: Unexpected token (22:16) You may need an appropriate loader to handle this file type.

这是我所有的babel依赖项:

{
  "dependencies": {
    "@babel/core": "^7.9.0",
    "@babel/node": "^7.8.7",
    "@babel/plugin-external-helpers": "^7.8.3",
    "@babel/plugin-proposal-class-properties": "^7.8.3",
    "@babel/plugin-proposal-decorators": "^7.8.3",
    "@babel/plugin-proposal-json-strings": "^7.8.3",
    "@babel/plugin-proposal-object-rest-spread": "^7.9.5",
    "@babel/plugin-proposal-optional-chaining": "^7.9.0",
    "@babel/plugin-syntax-dynamic-import": "^7.8.3",
    "@babel/plugin-syntax-import-meta": "^7.8.3",
    "@babel/plugin-transform-async-to-generator": "^7.8.3",
    "@babel/plugin-transform-modules-commonjs": "^7.9.0",
    "@babel/plugin-transform-react-constant-elements": "^7.9.0",
    "@babel/plugin-transform-react-inline-elements": "^7.9.0",
    "@babel/plugin-transform-runtime": "^7.9.0",
    "@babel/polyfill": "^7.8.7",
    "babel-plugin-add-module-exports": "^1.0.2",
    "babel-plugin-array-includes": "^2.0.3",
    "babel-plugin-inline-react-svg": "^1.1.1"
  }
}
  • 节点v14.0.0
  • npm 6.14.4
  • 反应脚本2.1.8

我还需要什么才能使它正常工作?

1 个答案:

答案 0 :(得分:1)

您只需要确保已经安装了react-scripts 3.3.0+ version,因为它已经内置了可选的链接。

const obj = { a: `Hello` };

// Hello World
const App = () => {
  return (
    <>
      {obj?.a}
      {obj?.b ?? ` World`}
    </>
  );
};

Edit nice-paper-74xbv