如何使用create-react-app创建17.0.2版本的项目

版权声明:本文为转载博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
文章转载出处:https://blog.csdn.net/assokoo123/article/details/127858583

目前,使用create-react-app创建的项目是18版本的,如果想使用17.0.2版本的,该如何创建呢?

  1. 创建项目 create-react-app my-demo
  2. 更改package.json文件
    • 首先将react和react-dom的版本降级,从18降到17
"dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0", //将13.4.0改为12.1.5
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.2.0", //将18.2.0改为17.0.2
    "react-dom": "^18.2.0", //将18.2.0改为17.0.2
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  1. 删除node_modules文件夹
  2. 重新安装依赖 npm i
    • 此时,终端警告:Could not resolve dependency: npm WARN peer react@"^18.0.0" from @testing-library/react@13.4.0
    • 然后再次降级package.json文件中的 @testing-library/react 的版本
"dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^12.1.5",
    "@testing-library/user-event": "^13.5.0",
    "react": "^17.0.2", //将18.2.0改为17.0.2
    "react-dom": "^17.0.2", //将18.2.0改为17.0.2
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  1. 删除node_modules文件夹并重新安装依赖
  2. 然后运行项目 npm start,报错:Module not found: Error: Can't resolve 'react-dom/client'
    • 修改src/index.js 文件
    import React from 'react';
    //使用此方式声明ReactDom
    import ReactDom from 'react-dom';
    // import ReactDOM from 'react-dom/client';
    import './index.css';
    import App from './App';
    import reportWebVitals from './reportWebVitals';
    
    //修改渲染路由的方式
    ReactDom.render(
      <App />,document.getElementById('root')
    );
    // const root = 	ReactDOM.createRoot(document.getElementById('root'));
    // root.render(
    //   <React.StrictMode>
    //     <App />
    //   </React.StrictMode>
    // );
    
    // If you want to start measuring performance in your app, pass a function
    // to log results (for example: reportWebVitals(console.log))
    // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
    reportWebVitals();
    
  3. 至此页面就运行起来了。
    在这里插入图片描述
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐