Optional Chaining Operator in React and babel

孤者浪人 提交于 2020-03-24 05:53:58

问题


In my project I config babel:

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

And this is my devDependencies in package.json:

"devDependencies": {
    "babel-cli": "^7.0.0-alpha.19",
    "babel-loader": "^7.1.5",
    "babel-plugin-module-resolver": "^3.1.1",
    "babel-plugin-transform-optional-chaining": "^7.0.0-beta.3",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-stage-1": "^6.24.1",
    "copy-webpack-plugin": "^4.5.2",
    "css-loader": "^1.0.0",
    "file-loader": "^1.1.11",
    "html-webpack-plugin": "^3.2.0",
    "prettier": "^1.14.2",
    "react-hot-loader": "^4.3.4",
    "style-loader": "^0.22.1",
    "url-loader": "^1.1.1",
    "webpack": "^4.16.5",
    "webpack-cli": "^3.1.0",
    "webpack-dev-server": "^3.1.5"
  }

When I run the project I get this error:

Cannot find module 'babel-preset-transform-optional-chaining'

Can anyone explain how to fix this error?


回答1:


transform-optional-chaining is a plugin (not a preset). Try changing your babel config to:

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



回答2:


It seems the bigger issue is you have a mix of versions of babel, all of which are outdated. "transform-optional-chaining" is already included in "stage-1" presets for babel 7 but was not back-ported to babel 6.

However, to make matters more confusing: babel has done away with stage-presets (and es201x presets were deprecated in Babel 6). So in the latest version of babel, you not only do need to list out "transform-optional-chaining", but also every other plugin you're using.

I think the only real option here (if you want to use the latest plugins) is to upgrade to the latest version of Babel 7 - which includes a lot of changes, but you'll have to do it eventually anyway. You can find a migration guide here.

I suppose you could find an alpha version before before stage-presets were removed but that's just giving yourself more work for the future, and there will likely still be changes that have to be made anyhow.



来源:https://stackoverflow.com/questions/52125711/optional-chaining-operator-in-react-and-babel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!