Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

babeljs - How to enable optional chaining with Create React App and TypeScript

Support for the experimental syntax 'optionalChaining' isn't currently enabled

I was getting the above error. I followed this post and added "@babel/plugin-proposal-optional-chaining": "^7.7.4" into my devDependencies.

Then I am getting this error,

Add @babel/plugin-proposal-optional-chaining (https://git.io/vb4Sk) to the 'plugins' section of your Babel config to enable transformation.

So I followed this post and added .babelrc file into my project's root

{
    "presets": ["react", "es2015","stage-1"],
    "plugins": ["transform-runtime", "transform-optional-chaining"]
}

This did not seem to do anything. I also heard someone mentioning that Create React App does not let you modify babel's configurations. So my question is how can I enable optional chaining without re-wiring the whole CRA?

P.S. I am using "typescript": "^3.7.2", or at least that is what my package.json says. I tried npm install to ensure it is updated. Not sure if CRA doing something weird underneath and using older version of TypeScript somehow.


EDIT: When I started the project with CRA, I believe we were using TypeScript: 3.6.x. I wanted to use Optional Chaining, so I changed my package.json file to "typescript": "^3.7.2" then npm install. I think the problem is, TypeScript knows that I am using 3.7.2, but CRA still have older configuration and I am not sure how I can update that.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Create-React-App uses babel to transpile the TypeScript so it isn't using your npm installed version of TypeScript. Version 3.3.0 of react-scripts supports TypeScript 3.7. You can install it and use it with:

  • yarn add react-scripts@3.3.0

    -or-

  • npm install -s react-scripts@3.3.0


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...