Giter Site home page Giter Site logo

elieladelrom / cra-template-must-have-libraries Goto Github PK

View Code? Open in Web Editor NEW
100.0 2.0 22.0 168 KB

✨ A starter CRA professional React v17 project with must-have ReactJS libraries including TypeScript, SCSS, Redux, Toolkit, Material-UI, Styled Components, React Router, Jest & Enzym, Folder structure, Generate templates, ESLint, Prettier, Recoil

Home Page: https://elielrom.com

License: MIT License

HTML 5.11% TypeScript 87.95% JavaScript 3.57% SCSS 2.83% Shell 0.12% Dockerfile 0.43%
cra cra-template react reactjs-libraries

cra-template-must-have-libraries's Introduction

CRA-MHL

A Professional Starter Create React App (CRA) with Must-Have Libraries (MHL) Template

Build Status Coverage Status test CI build npm version GitHub issues DeepScan grade codecov - Get Badges

A very opinionated starter Create React App (CRA) template with Must-Have Libraries (MHL) including:

  • React v17.0.2
  • Type Checker - TypeScript ^4.2.3
  • Preprocessors - Sass/SCSS
  • State management - Redux Toolkit, Recoil
  • CSS Framework - Material-UI
  • CSS-in-JS Modules — Styled Components
  • Router - React Router
  • Unit Testing - Jest & Enzyme + Sinon
  • E2E Testing - Jest & Puppeteer
  • Folder structure
  • Generate templates
  • Format & Lint - ESLint & Prettier
  • Useful utilities - Moment, Classnames, Serve, react-snap, React-Helmet, Analyzer Bundle, react-uuid.

Custom Templates, format, and ESLint configurations. The original Create React App README available here.

If you want to generate HTML in the server check NEXT-MHL

Usage

yarn create react-app your-project-name --template must-have-libraries

Or;

npx create-react-app your-project-name --template must-have-libraries

npx package runner tool installs the most recent stable version of CRA from npm. (npx comes out of the box with npm 5.2+)

--template parameter points to this template, note that cra-template- prefix will be omitted.

What are React Developer must know libraries and why do I need them?

Create-React-App (CRA) is a great starter project for React, you can be up and running quickly. It includes vanilla flavor packages and other opinionated packages. Additionally, it has an option to include templates or you can create your own template.

CRA already made some decisions for us, for example; build tools: Webpack over Rollup or Parcel. Task Runners npm scripts over gulp. CSS, JS, and Jest as the default, and so on.

After working & reviewing projects and libraries that help get the job done with React, it’s hard to stay neutral and not to form an opinion one way or another.

For example, when using the package manager what should you use: yarn or npm. When it comes to CSS preprocessor: Saas/SCSS, PostCSS, Less or Stylus, or maybe others. CSS Frameworks: use the main ones; Bootstrap or MaterialUI or a different one. The list goes on and on.

Another challenge I observe is that many libraries are not very easy to migrate to once you start without them so although you may not need them today, it may be worth looking into starting on the right foot.

The idea here is to help you set up CRA with the selection of certain opinionated libraries that will help you get the job done from a small project to a larger enterprise level.

Run Scripts

Inside the project directory run using npm or yarn:

  • start - runs the app in the development mode. Open http://localhost:3000 to view it in the browser.
  • test - launches the test runner in the interactive watch mode.
  • build - builds the app for production to the build folder.
  • build:serve - run a local static build using the production build using serve library. Install npm install -g serve.
  • build:profile - profiling production build.
  • eject - exposes content of react-script package
  • lint - lints project files according to Airbnb — as part of their style guide 👍 — it provides an ESLint configuration that anyone can use and it is the standard.
  • fix - fix lints issues according to style guide set.
  • format - will format your code prettier using opinionated settings inside .prettierrc file.
  • isready - will check if the code is ready for showtime (production), run lint, format and build.
  • test:e2e - run e2e integration testing with the help of Jest & Puppeteer.
  • test:e2e-watch - same as test:e2e just with a watcher.
  • test:e2e-alone - stand-alone e2e integration testing NodeJS script for testing using Puppeteer.
  • test:debug - debug your jest tests using the debugger statement, more info here.
  • coverage - this test is to create a coverage report at needs extra setting in order to work as expected.
  • analyze - source-map-explorer to Analyzer Bundle.
  • analyzer - uses cra-bundle-analyzer to Analyzer Bundle.

CRA template only support scripts and dependencies inside generated package.json. No devDependencies is possible on CRA template for now.

Docker

Docker hub: https://hub.docker.com/repository/docker/elieladelrom/cra-template-must-have-libraries

Check project running: http://localhost:8080/

$ docker run -p 8080:80 elieladelrom/cra-template-must-have-libraries

Need bootstrap?

If you need bootstrap. Just add;

$ yarn add bootstrap

Uncomment import in index.tsx;

import 'bootstrap/dist/css/bootstrap.css';

More here: https://create-react-app.dev/docs/adding-bootstrap

Router + State Management

Router via React Router v5.2.0 and is set on 'AppRouter.tsx' and included in 'index.tsx', read here.

The code is set for Recoil or Redux Toolkit you pick.

Unit Testing

Unit Testing supported with Enzyme that works with Jest. Additionally, Sinon - a standalone test spies, stubs and mocks that works with Enzyme & Jest.

Jest and Sinon serve the same purpose. So why add Sinon? The answer is that there are times that you may find one framework more natural and easier to work for the specific test you need than the other so it wouldn’t hurt to have both.

You can compare the list of APIs on Jest (https://jestjs.io/docs/en/api) and Sinon (https://sinonjs.org/releases/v9.2.0/)

The 'src/setupTests.ts' file is already configured to work with enzyme using the enzyme react adapter.

For snapshot -- update 'package.json';

// package.json
  "jest": {
    "snapshotSerializers": ["enzyme-to-json/serializer"]
  }

Note: remember to update / delete 'src/App.test.tsx' in case you update 'App.tsx'

For instance to check if a component you added include in App.tsx;

import { shallow } from "enzyme";
import Calculator from "./components/SomeComponent/SomeComponent";

test('should render SomeComponent', () => {
  const wrapper = shallow(<App />);
  const calculator = wrapper.find(SomeComponent);
  expect(calculator.exists()).toBe(true);
})

You can read more about unit testing: hello-jest-enzyme-ts

To run the tests:

$ yarn test

Coverage

To set coverage we can use Jest. Jest allow us to create reports in different format and set where we want to collect these reports from (or not collect them from), as well as ensure the coverageThreshold. Take a look at my 'package.json' settings;

To get testing coverage report, you need to include the following settings in your 'package.json' file;

// package.json
"jest": {
  "coverageReporters": [
    "json",
    "text",
    "html",
    "lcov"
  ],
  "collectCoverageFrom": [
    "src/**/*.{js,jsx,ts,tsx}",
    "!src/**/*/*.d.ts",
    "!src/**/*/Loadable.{js,jsx,ts,tsx}",
    "!src/**/*/types.ts",
    "!src/**/store.ts",
    "!src/index.tsx",
    "!src/serviceWorker.ts",
    "!<rootDir>/node_modules/",
    "!**/templates/**",
    "!**/template/**"
  ],
  "coverageThreshold": {
    "global": {
      "branches": 50,
      "functions": 50,
      "lines": 50,
      "statements": 50
    }
  }

In this example, I am enforcing 50% 'coverageThreshold', when I set these it can ensure that I am testing in within my threshold or get an error. That can come handy, because we can set these setting to ensure that every single function, statement, lines and branches get at least 50% or even set it to 100% test coverage.

E2E Testing

E2E testing provided by Jest & Puppeteer. Check the E2E folder for stand-alone and testing app.test.tsx component. You can read more about it here.

To run the E2E stand-alone and Jest & Puppeteer tests run;

$ yarn test:e2e

And;

$ yarn test:e2e-alone

Eslint configurations

Lint set according to Airbnb style guide — as part of their style guide. Feel free to tweak .eslintrc.

Format configurations

Prettier is set using my opinionated settings, feel free to tweak prettier rules inside config file .prettierrc to match your code style.

Configure Components Templates

generate-react-cli help speed up productivity in React projects, feel free to tweak rules inside the config file generate-react-cli.json to match your needs.

Debugging and Profiling

There are many options to debug such as using this run script and placing debugger statements $ yarn test:debug. Read how on how to debug the App in this article.

For Profiling you can use methods such as Chrome DevTools or the <Profile> Component. Here is an example;

// src/AppRouter.tsx

import { Profiler } from 'react'

const AppRouter: FunctionComponent = () => {
  return (
    <Profiler onRender={(id, phase, actualTime, baseTime, startTime, commitTime) => {
      console.log(`${id}'s ${phase} phase:`);
      console.log(`Actual time: ${actualTime}`);
      console.log(`Base time: ${baseTime}`);
      console.log(`Start time: ${startTime}`);
      console.log(`Commit time: ${commitTime}`);
    }}>
    <Router>
      <RecoilRoot>
        <Suspense fallback={<span>Loading...</span>}>
          <Switch>
            <Route exact path="/" component={App} />
          </Switch>
        </Suspense>
      </RecoilRoot>
    </Router>
    </Profiler>
  )
}

Read more about profiling options here.

Optimizing

  • Prerender - almost static pages using react-snap. See comments in: src/index.tsx;
  • Precache - src/index.tsx > serviceWorker.register()
  • Analyzer Bundle - yarn add -D cra-bundle-analyzer -> Create the report: npx cra-bundle-analyzer

Read more about optimizing in this article.

Analyzing the Bundle Size

‘bundle-analyzer’ (https://github.com/svengau/cra-bundle-analyzer), is my prefer bundle analyzer, it's more colorful and includes all the bundles in one page instead of calling them one by one with source-map-explorer.

Install (yarn add --dev cra-bundle-analyzer) & you use the run script:

$ yarn analyzer

Other option is to use source-map-explorer (yarn add --dev source-map-explorer);

$ yarn analyze

Cost

Adding all these libraries from this project comes with a cost of 87 kb out of the gate (54 kb of that for Recoil).

Important - if you don't use Recoil - remove it:

$ yarn remove recoil

React v17 costs are a split between React library itself parsed cost 129.17KB that is broken down to parsed 8.67kb (or 2.4 gzipped) and the React DOM parsed 120.5kb (or 38kb gzipped).

If you can use help with your React project or have a burning question, or an issue in your project that needs help with, I invite you to hire me as your Coach. My strategy is 100% results-oriented. If you want to sample how I work 1-on-1, let’s schedule a one-time deep dive Consultation. Additionally, I will tutor you in react, javascript, typescript, mongodb, node, d3.

Where to go from here?

If you like this library, don't be shy to star it 🙏

cra-template-must-have-libraries's People

Contributors

andrewstec avatar elieladelrom avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

cra-template-must-have-libraries's Issues

Failed to resolve dependency tree: peerOptional typescript@"^3.2.1" from [email protected]

I am currently running into this issue when using this template. I do not know enough to really provide more insight or fix for this issue. However, I am able to successfully use the typescript template.

I get the same error when running the command outside of any project and by calling create-react-app test --template must-have-libraries

pnpm dlx create-react-app test --template must-have-libraries
Packages: +67
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Packages are hard linked from the content-addressable store to the virtual store.
  Content-addressable store is at: /tmp/.pnpm-store/v3
  Virtual store is at:             node_modules/.pnpm

/tmp/dlx-5476/5:
+ create-react-app 5.0.0

Progress: resolved 67, reused 67, downloaded 0, added 67, done

Creating a new React app in /home/paulw/test.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template-must-have-libraries...

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! Found: [email protected]
npm ERR! node_modules/typescript
npm ERR!   typescript@"4.2.3" from [email protected]
npm ERR!   node_modules/cra-template-must-have-libraries
npm ERR!     cra-template-must-have-libraries@"*" from the root project
npm ERR!   peerOptional typescript@"^3.2.1 || ^4" from [email protected]
npm ERR!   node_modules/react-scripts
npm ERR!     react-scripts@"*" from the root project
npm ERR!   3 more (ts-jest, tsutils, fork-ts-checker-webpack-plugin)
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peerOptional typescript@"^3.2.1" from [email protected]
npm ERR! node_modules/cra-template-must-have-libraries/node_modules/react-scripts
npm ERR!   react-scripts@"3.4.1" from [email protected]
npm ERR!   node_modules/cra-template-must-have-libraries
npm ERR!     cra-template-must-have-libraries@"*" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR! 
npm ERR! See /home/paulw/.npm/eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/paulw/.npm/_logs/2022-01-08T19_10_16_627Z-debug.log

Aborting installation.
  npm install --no-audit --save --save-exact --loglevel error react react-dom react-scripts cra-template-must-have-libraries has failed.

Filename issues with custom components

Hi,

While trying to use a custom component using:

npx generate-react-cli component HelloD3 --type=d3

The generated component tree looks like this:

HelloD3
├── component.tsx
├── style.scss
└── test.tsx

These names should apparently be HelloD3.[tsx|scss] for the rest of the code to work. I think this might be an issue with generate-react-cli but I'm not sure if this can be handled with the config. The documentation does describe a TemplateName special keyword, but it seems to apply to the component type (d3), and not hte component name (HelloD3).

Installation fails at node-sass

Hello, thanks for your project. I'm trying to follow the steps in this book: https://www.apress.com/gp/book/9781484270516

The installer fails at the node-sass step.
There's a lot of information printed but I think the important bit is

error /home/{usr}/workspace/javascript/react/integratingd3withreact/your-project-name/node_modules/node-sass: Command failed.
Exit code: 1
Command: node scripts/build.js

error.txt

❯ yarn -v
1.22.11

yarn add node-sass completes without error. I'm not sure what I should try.

wont build Mac

error [email protected]: The engine "node" is incompatible with this module. Expected version "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0". Got "14.6.0"
error Found incompatible module.

build aborts then reverts,
Mac 11.2.2
node v14.6.0
yarn 1.22.5

Can't install on M1

I have 2 macbooks- intel & M1

For intel one, I can install MHL without any problem
For M1, I got this error

error /Users/yuenkit/Bhere/temp/your-project-name/node_modules/node-sass: Command failed.
Exit code: 1
Command: node scripts/build.js
Arguments:
Directory: /Users/yuenkit/Bhere/temp/your-project-name/node_modules/node-sass
Output:
Building: /Users/yuenkit/.nvm/versions/node/v18.2.0/bin/node /Users/yuenkit/Bhere/temp/your-project-name/node_modules/node-gyp/bin/node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library=
gyp info it worked if it ends with ok
...
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp verb cli [
npm ERR! gyp verb cli   '/Users/yuenkit/.nvm/versions/node/v18.2.0/bin/node',
npm ERR! gyp verb cli   '/Users/yuenkit/Bhere/temp/react-d3-hello-world/node_modules/node-gyp/bin/node-gyp.js',

My laptop configuration:
node = v18.2.0

TypeScript dependency conflict with npm 7 / node 14

If I run npx create-react-app my-app --template must-have-libraries with npm 7.9.0 / node 14.16.0 (also tested with npm 7.6.0), I get the following dependency resolution error:

Could not resolve dependency:
peerOptional typescript@"^3.2.1" from [email protected]
node_modules/cra-template-must-have-libraries/node_modules/react-scripts
  react-scripts@"3.4.1" from [email protected]
  node_modules/cra-template-must-have-libraries
    cra-template-must-have-libraries@"*" from the root project

The full eresolve-report.txt is attached.

Using npm 6.14.12 / node 12.22.1, creation of the app succeeds.

First I suspected this to be a regression of facebook/create-react-app#9964, but npx create-react-app my-app --template typescript succeeds using npm 7 / node 14 as well. It therefore is specific to cra-template-must-have-libraries.

Having some difficulty using this on an M1 mac

This looks like a great library, but it doesn't seem to want to install on an M1 mac because puppeteer is hard-coded to be version 5.x. Prior to version 10 of puppeteer there was a bug that prevented the download of chromium and failed out, so upgrading to 10+ would resolve, but since this is a library/template there's no opportunity to upgrade it at install time.

Any chance you could add the caret to the version so it'll accept a later version of puppeteer if already installed, or better yet, upgrade puppeteer to latest and resolve any issues with that?

`

[email protected] preinstall /Volumes/repo/my-must-have-app/node_modules/yarn
:; (node ./preinstall.js > /dev/null 2>&1 || true)

[email protected] install /Volumes/repo/my-must-have-app/node_modules/cra-template-must-have-libraries/node_modules/puppeteer
node install.js

The chromium binary is not available for arm64:
If you are on Ubuntu, you can install with:

apt-get install chromium-browser

/Volumes/repo/my-must-have-app/node_modules/cra-template-must-have-libraries/node_modules/puppeteer/lib/cjs/puppeteer/node/BrowserFetcher.js:112
throw new Error();
^

`

Create app from the template doesn't work

Versions:
NPM - 8.19.2

Run command:

npx create-react-app web --template cra-template-must-have-libraries

Error log:

Installing template dependencies using npm...
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! While resolving: [email protected]
npm ERR! Found: @typescript-eslint/[email protected]
npm ERR! node_modules/@typescript-eslint/eslint-plugin
npm ERR!   @typescript-eslint/eslint-plugin@"3.8.0" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer @typescript-eslint/eslint-plugin@"2.x" from [email protected]
npm ERR! node_modules/eslint-config-react-app
npm ERR!   eslint-config-react-app@"5.2.1" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR! 
npm ERR! See /home/user/.npm/eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/user/.npm/_logs/2022-10-02T18_15_58_263Z-debug-0.log
`npm install --no-audit --save @babel/[email protected] @material-ui/[email protected] @material-ui/[email protected] @octokit/[email protected] @octokit/[email protected] @reduxjs/[email protected] @testing-library/[email protected] @testing-library/[email protected] @testing-library/[email protected] @types/[email protected] @types/[email protected] @types/[email protected] @types/[email protected] @types/[email protected] @types/[email protected] @types/[email protected] @types/[email protected] @types/[email protected] @types/[email protected] @types/[email protected] @typescript-eslint/[email protected] @typescript-eslint/[email protected] @wojtekmaj/[email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] @types/[email protected] @types/[email protected] @types/[email protected] [email protected] [email protected]` failed

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.