Чт. Янв 20th, 2022

    Настройка локальной среды разработки.

    $npm i -g create-react-app

    создадим каталог для приложений React

    $mkdir Projects
    $cd Projects
    $create-react-app react-quiz
    

    Столкнулся с ошибкой выполнения скрипта под Windows 10

    create-react-app : Невозможно загрузить файл C:\Users\andre\AppData\Roaming\npm\create-react-app.ps1, так как выполнени
    е сценариев отключено в этой системе. Для получения дополнительных сведений см. about_Execution_Policies по адресу http
    s:/go.microsoft.com/fwlink/?LinkID=135170.
    строка:1 знак:1
    + create-react-app react-quiz
    + ~~~~~~~~~~~~~~~~
    + CategoryInfo : Ошибка безопасности: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess

    Решение проблемы запуска :

    1. запускаем PowerShell от имени Администратора и даем команду
    2. Set-ExecutionPolicy -ExecutionPolicy unrestricted
    Изменение политики выполнения
    Политика выполнения защищает компьютер от ненадежных сценариев. Изменение политики выполнения может поставить под
    угрозу безопасность системы, как описано в разделе справки, вызываемом командой about_Execution_Policies и
    расположенном по адресу https:/go.microsoft.com/fwlink/?LinkID=135170 . Вы хотите изменить политику выполнения?
    [Y] Да - Y [A] Да для всех - A [N] Нет - N [L] Нет для всех - L [S] Приостановить - S [?] Справка
    (значением по умолчанию является "N"):Y

    После этого уже спокойно можно выполнить скрипт, например, из терминала VisualStudioCode

    create-react-app  react-quiz

    Installing packages. This might take a couple of minutes.
    Installing react, react-dom, and react-scripts with cra-template...
    
    yarn add v1.21.1
    [1/4] Resolving packages...
    [2/4] Fetching packages...
    info fsevents@1.2.12: The platform "win32" is incompatible with this module.
    info "fsevents@1.2.12" is an optional dependency and failed compatibility check. Excluding it from installation.
    info fsevents@2.1.2: The platform "win32" is incompatible with this module.
    info "fsevents@2.1.2" is an optional dependency and failed compatibility check. Excluding it from installation.
    [3/4] Linking dependencies...
    warning "react-scripts > @typescript-eslint/eslint-plugin > tsutils@3.17.1" has unmet peer dependency "typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta".
    [4/4] Building fresh packages...
    success Saved lockfile.
    warning Your current version of Yarn is out of date. The latest version is "1.22.5", while you're on "1.21.1".
    info To upgrade, run the following command:
    $ curl --compressed -o- -L https://yarnpkg.com/install.sh | bash
    success Saved 22 new dependencies.
    info Direct dependencies
    ├─ cra-template@1.0.3
    ├─ react-dom@16.14.0
    ├─ react-scripts@3.4.3
    └─ react@16.14.0
    info All dependencies
    ├─ @babel/plugin-syntax-typescript@7.10.4
    ├─ @babel/plugin-transform-flow-strip-types@7.9.0
    ├─ @babel/plugin-transform-runtime@7.9.0
    ├─ @babel/plugin-transform-typescript@7.12.0
    ├─ @babel/preset-typescript@7.9.0
    ├─ babel-preset-react-app@9.1.2
    ├─ cra-template@1.0.3
    ├─ eslint-config-react-app@5.2.1
    ├─ html-entities@1.3.1
    ├─ loglevel@1.7.0
    ├─ portfinder@1.0.28
    ├─ react-dev-utils@10.2.1
    ├─ react-dom@16.14.0
    ├─ react-error-overlay@6.0.7
    ├─ react-scripts@3.4.3
    ├─ react@16.14.0
    ├─ scheduler@0.19.1
    ├─ serialize-javascript@4.0.0
    ├─ sockjs@0.3.20
    ├─ spdy@4.0.2
    ├─ terser-webpack-plugin@2.3.8
    └─ webpack-dev-server@3.11.0
    Done in 81.70s.
    Git repo not initialized Error: Command failed: git --version
    at checkExecSyncError (child_process.js:611:11)
    at execSync (child_process.js:647:15)
    at tryGitInit (C:\Projects\react-quiz\node_modules\react-scripts\scripts\init.js:46:5)
    at module.exports (C:\Projects\react-quiz\node_modules\react-scripts\scripts\init.js:266:7)
    at [eval]:3:14
    at Script.runInThisContext (vm.js:120:20)
    at Object.runInThisContext (vm.js:311:38)
    at Object.<anonymous> ([eval]-wrapper:10:26)
    at Module._compile (internal/modules/cjs/loader.js:1151:30)
    at evalScript (internal/process/execution.js:94:25) {
    status: 1,
    signal: null,
    output: [ null, null, null ],
    pid: 14816,
    stdout: null,
    stderr: null
    }
    
    Installing template dependencies using yarnpkg...
    yarn add v1.21.1
    [1/4] Resolving packages...
    warning @testing-library/react > @types/testing-library__react > @types/testing-library__dom@7.5.0: This is a stub types definition. testing-library__dom provides its own type definitions, so you do not need this installed.
    [2/4] Fetching packages...
    info fsevents@2.1.2: The platform "win32" is incompatible with this module.
    info "fsevents@2.1.2" is an optional dependency and failed compatibility check. Excluding it from installation.
    info fsevents@1.2.12: The platform "win32" is incompatible with this module.
    info "fsevents@1.2.12" is an optional dependency and failed compatibility check. Excluding it from installation.
    [3/4] Linking dependencies...
    warning "react-scripts > @typescript-eslint/eslint-plugin > tsutils@3.17.1" has unmet peer dependency "typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta".
    warning " > @testing-library/user-event@7.2.1" has unmet peer dependency "@testing-library/dom@>=5".
    [4/4] Building fresh packages...
    success Saved lockfile.
    success Saved 23 new dependencies.
    info Direct dependencies
    ├─ @testing-library/jest-dom@4.2.4
    ├─ @testing-library/react@9.5.0
    ├─ @testing-library/user-event@7.2.1
    ├─ react-dom@16.14.0
    └─ react@16.14.0
    info All dependencies
    ├─ @babel/runtime-corejs3@7.12.0
    ├─ @sheerun/mutationobserver-shim@0.3.3
    ├─ @testing-library/dom@6.16.0
    ├─ @testing-library/jest-dom@4.2.4
    ├─ @testing-library/react@9.5.0
    ├─ @testing-library/user-event@7.2.1
    ├─ @types/aria-query@4.2.0
    ├─ @types/prop-types@15.7.3
    ├─ @types/react-dom@16.9.8
    ├─ @types/react@16.9.52
    ├─ @types/testing-library__dom@7.5.0
    ├─ @types/testing-library__react@9.1.3
    ├─ aria-query@4.2.2
    ├─ css.escape@1.5.1
    ├─ csstype@3.0.3
    ├─ dom-accessibility-api@0.3.0
    ├─ lz-string@1.4.4
    ├─ min-indent@1.0.1
    ├─ react-dom@16.14.0
    ├─ react@16.14.0
    ├─ redent@3.0.0
    ├─ strip-indent@3.0.0
    └─ wait-for-expect@3.0.2
    Done in 28.20s.
    Removing template package using yarnpkg...
    
    yarn remove v1.21.1
    [1/2] Removing module cra-template...
    [2/2] Regenerating lockfile and installing missing dependencies...
    info fsevents@2.1.2: The platform "win32" is incompatible with this module.
    info "fsevents@2.1.2" is an optional dependency and failed compatibility check. Excluding it from installation.
    info fsevents@1.2.12: The platform "win32" is incompatible with this module.
    info "fsevents@1.2.12" is an optional dependency and failed compatibility check. Excluding it from installation.
    warning " > @testing-library/user-event@7.2.1" has unmet peer dependency "@testing-library/dom@>=5".
    warning "react-scripts > @typescript-eslint/eslint-plugin > tsutils@3.17.1" has unmet peer dependency "typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta".
    success Uninstalled packages.
    Done in 19.60s.
    
    Success! Created react-quiz at C:\Projects\react-quiz
    Inside that directory, you can run several commands:
    
    yarn start
    Starts the development server.
    
    yarn build
    Bundles the app into static files for production.
    
    yarn test
    Starts the test runner.
    
    yarn eject
    Removes this tool and copies build dependencies, configuration files
    and scripts into the app directory. If you do this, you can’t go back!
    
    We suggest that you begin by typing:
    
    cd react-quiz
    yarn start
    
    Happy hacking!
    

    Открываем папку проекта в Visual Studio

    Visual Studio

    Открываем консоль <CTRL>+<J> и выполняем команду:

    $ yarn eject
    yarn run v1.21.1
    $ react-scripts eject
    NOTE: Create React App 2+ supports TypeScript, Sass, CSS Modules and more without ejecting: https://reactjs.org/blog/2018/10/01/create-react-app-v2.html
    
    ? Are you sure you want to eject? This action is permanent. Yes
    Ejecting...
    
    Copying files into C:\Projects\react-quiz
    Adding \config\env.js to the project
    Adding \config\getHttpsConfig.js to the project
    Adding \config\modules.js to the project
    Adding \config\paths.js to the project
    Adding \config\pnpTs.js to the project
    Adding \config\webpack.config.js to the project
    Adding \config\webpackDevServer.config.js to the project
    Adding \config\jest\cssTransform.js to the project
    Adding \config\jest\fileTransform.js to the project
    Adding \scripts\build.js to the project
    Adding \scripts\start.js to the project
    Adding \scripts\test.js to the project
    
    Updating the dependencies
    Removing react-scripts from dependencies
    Adding @babel/core to dependencies
    Adding @svgr/webpack to dependencies
    Adding @typescript-eslint/eslint-plugin to dependencies
    Adding @typescript-eslint/parser to dependencies
    Adding babel-eslint to dependencies
    Adding babel-jest to dependencies
    Adding babel-loader to dependencies
    Adding babel-plugin-named-asset-import to dependencies
    Adding babel-preset-react-app to dependencies
    Adding camelcase to dependencies
    Adding case-sensitive-paths-webpack-plugin to dependencies
    Adding css-loader to dependencies
    Adding dotenv to dependencies
    Adding dotenv-expand to dependencies
    Adding eslint to dependencies
    Adding eslint-config-react-app to dependencies
    Adding eslint-loader to dependencies
    Adding eslint-plugin-flowtype to dependencies
    Adding eslint-plugin-import to dependencies
    Adding eslint-plugin-jsx-a11y to dependencies
    Adding eslint-plugin-react to dependencies
    Adding eslint-plugin-react-hooks to dependencies
    Adding file-loader to dependencies
    Adding fs-extra to dependencies
    Adding html-webpack-plugin to dependencies
    Adding identity-obj-proxy to dependencies
    Adding jest to dependencies
    Adding jest-environment-jsdom-fourteen to dependencies
    Adding jest-resolve to dependencies
    Adding jest-watch-typeahead to dependencies
    Adding mini-css-extract-plugin to dependencies
    Adding optimize-css-assets-webpack-plugin to dependencies
    Adding pnp-webpack-plugin to dependencies
    Adding postcss-flexbugs-fixes to dependencies
    Adding postcss-loader to dependencies
    Adding postcss-normalize to dependencies
    Adding postcss-preset-env to dependencies
    Adding postcss-safe-parser to dependencies
    Adding react-app-polyfill to dependencies
    Adding react-dev-utils to dependencies
    Adding resolve to dependencies
    Adding resolve-url-loader to dependencies
    Adding sass-loader to dependencies
    Adding semver to dependencies
    Adding style-loader to dependencies
    Adding terser-webpack-plugin to dependencies
    Adding ts-pnp to dependencies
    Adding url-loader to dependencies
    Adding webpack to dependencies
    Adding webpack-dev-server to dependencies
    Adding webpack-manifest-plugin to dependencies
    Adding workbox-webpack-plugin to dependencies
    
    Updating the scripts
    Replacing "react-scripts start" with "node scripts/start.js"
    Replacing "react-scripts build" with "node scripts/build.js"
    Replacing "react-scripts test" with "node scripts/test.js"
    
    Configuring package.json
    Adding Jest configuration
    Adding Babel preset
    
    Running yarn...
    [1/4] Resolving packages...
    [2/4] Fetching packages...
    info fsevents@1.2.12: The platform "win32" is incompatible with this module.
    info "fsevents@1.2.12" is an optional dependency and failed compatibility check. Excluding it from installation.
    info fsevents@2.1.2: The platform "win32" is incompatible with this module.
    info "fsevents@2.1.2" is an optional dependency and failed compatibility check. Excluding it from installation.
    [3/4] Linking dependencies...
    warning " > @testing-library/user-event@7.2.1" has unmet peer dependency "@testing-library/dom@>=5".
    warning "@typescript-eslint/eslint-plugin > tsutils@3.17.1" has unmet peer dependency "typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta".
    [4/4] Building fresh packages...
    success Saved lockfile.
    Ejected successfully!
    
    fatal: not a git repository (or any of the parent directories): .git
    Staged ejected files for commit.
    
    Please consider sharing why you ejected in this survey:
    http://goo.gl/forms/Bi6CZjk1EqsdelXk1
    
    Done in 29.42s.

    Для того, чтобы пользоваться различными  нативными конфигурациями webpackа, которые есть в create-react-app и пользоваться css-модулями.

    Затем

    $ yarn install
    yarn install v1.21.1
    [1/4] Resolving packages...
    success Already up-to-date.
    Done in 1.12s.

    Чтобы обновить список зависимостей и наконец запускаем приложение командой

    $ yarn start

    Теперь немного почистим вновь созданный проект.

    Удаляем в папке src файл App.test.js (тесты пока делать не будем), также удаляем logo.svg, App.css и в принципе все.

    Теперь в index.js у нас есть база которая нас интересует, у нас рендерится App компонент.

    Убираем в App.js строки:

    import logo from './logo.svg';
    import './App.css';
    и очистим целиком раздел с кодом приложения, добавляя строку для проверки Hello React
        <div className="App">
          <h1>Hello React</h1>
        </div>
    Видим в окне браузера надпись Hello React. Поздравляю, вы создали первое простейшее приложение на ReactJS.

    Создание компонента Layout

    Создаем компонент, который будет содержать разметку всего нашего приложения. Это будет компонент высокого порядка, поэтому создаем его в папке hoc
    В ней создаем подпапку Layout и в ней уже файл Layout.js.

    от Andrew