メインコンテンツまでスキップ

2022年12月になってもcreate-react-appでReact 17を新規作成したい

· 約3分
moritalous

Reactプロジェクトの作成

まずはcreate-react-appを実行します。

npx create-react-app app --template typescript

React 18で作成されます。

package.json
{
"name": "app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.2",
"@types/node": "^16.18.6",
"@types/react": "^18.0.26",
"@types/react-dom": "^18.0.9",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"typescript": "^4.9.3",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

React 17にダウングレード

  1. package.jsondependenciesを修正します。

       "dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    - "@testing-library/react": "^13.4.0",
    + "@testing-library/react": "^12.0.0",
    "@testing-library/user-event": "^13.5.0",
    "@types/jest": "^27.5.2",
    "@types/node": "^16.18.6",
    - "@types/react": "^18.0.26",
    - "@types/react-dom": "^18.0.9",
    - "react": "^18.2.0",
    - "react-dom": "^18.2.0",
    + "@types/react": "^17.0.0",
    + "@types/react-dom": "^17.0.0",
    + "react": "^17.0.0",
    + "react-dom": "^17.0.0",
    "react-scripts": "5.0.1",
    "typescript": "^4.9.3",
    "web-vitals": "^2.1.4"
    },
  2. パッケージを再インストール

    cd app
    rm -rf node_modules
    npm i
  3. index.tsxを修正

    修正前
    import React from 'react';
    import ReactDOM from 'react-dom/client';
    import './index.css';
    import App from './App';
    import reportWebVitals from './reportWebVitals';

    const root = ReactDOM.createRoot(
    document.getElementById('root') as HTMLElement
    );
    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();
    修正後
    import React from 'react';
    import ReactDOM from 'react-dom';
    import './index.css';
    import App from './App';
    import reportWebVitals from './reportWebVitals';

    const root = document.getElementById('root');

    ReactDOM.render(
    <React.StrictMode>
    <App />
    </React.StrictMode>,
    root
    );

    // 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();

以上で完成です。

image.png