Coder Social home page Coder Social logo

nimahkh / react-cool-starter Goto Github PK

View Code? Open in Web Editor NEW

This project forked from wellyshen/react-cool-starter

0.0 1.0 0.0 7.11 MB

😎🐣 A starter boilerplate for a universal web app with the best development experience and a focus on performance and best practices.

License: MIT License

JavaScript 19.58% CSS 1.94% TypeScript 77.92% Dockerfile 0.57%

react-cool-starter's Introduction

React Cool Starter

πŸŽ‰ react-cool-img is online, which is a lightweight but powerful <Img /> component for image UX and performance optimization.

A simple but feature rich starter boilerplate for creating your own universal app. It built on the top of React, Redux, React Router and Express. Includes all the hot stuff and modern web development tools such as Typescript, Webpack, Babel, PostCSS, React Hot Loader, Jest and Redux Devtools Extension. See the β€œFeatures” section for other awesome features you can expect.

I will maintain the starter boilerplate and keep all of the technologies on trend. Welcome to join me if you want. Hope you guys love it 🀩

πŸ‘» I'm curious what kind of app that you guys building via this starter? Please feel free to tell me, let's make some sharing between us.

build status coverage status dependencies status devDependencies status code style: prettier MIT licensed All Contributors PRs welcome Twitter URL

Real Case Study

  • Rendah Mag is a music magazine which exists to bring exposure to an ever-growing community, focusing on the latest Halftime, Beats & Experimental news & releases. Congrats for the amazing product. 🎧 πŸŽ‰
  • BECK Friends is an international delivery service, which is built based on this starter boilerplate. Congrats for successful migrating to React. πŸŽ‰
  • DealDrop is the best place to find verified coupon codes, deals, promos and offers for thousands of stores & brands you love. Never pay full price again πŸ€‘

Features

Really cool starter boilerplate with the most popular technologies:

  • Universal rendering with async data fetching.
  • React as the view framework.
  • Redux as the state management.
  • React Router as the router.
  • Connected React Router to bind Redux with React Router. Refer to doc to see how it works.
  • Express server.
  • Typescript as the static type checker for Javascript.
  • Webpack for app bundling.
  • Babel for transpile ES6+ to ES5.
  • React Hot Loader to tweak React components in real time.
  • nodemon to monitor for any changes in your Node.js application and automatically restart the server.
  • axios as the Promise-based HTTP client for the browser and Node.js.
  • redux-thunk as the middleware to deal with asynchronous action.
  • react-helmet to manage title, meta, styles and scripts tags on both server and client.
  • loadable-component to lazy load component when needed in app. Reduce your bundle size without stress.
  • Webpack Dev Middleware serves the files emitted from webpack over the Express server.
  • Webpack Hot Middleware allows you to add hot reloading into the Express server.
  • css-modules-require-hook compiles CSS Modules in runtime for SSR.
  • asset-require-hook allows your assets files required during runtime for SSR.
  • assets-webpack-plugin generates assets with hash so you can use them for SSR.
  • Webpack Bundle Analyzer creates a visualize size of webpack output files with an interactive zoomable treemap.
  • helmet helps secure Express apps with various HTTP headers.
  • morgan the HTTP request logger for server side debugging.
  • Redux Devtools Extension for debugging application's state changes.
  • ESLint to maintain a consistent Typescript/Javascript code style (with Airbnb configuration).
  • StyleLint to maintain a consistent css/scss code style.
  • Prettier to format code and style.
  • CSS and SASS support with PostCSS for advanced transformations (e.g. autoprefixer, cssnext etc.). CSS modules enabled.
  • Image (with imagemin-webpack-plugin for compressing images with imagemin) and Font support.
  • Split vendor's libraries from client bundle.
  • No other view engines, just Javascript based HTML rendering component.
  • Shared app config between development and production.
  • 404 error page and redirect handling.
  • Integrate Jest with enzyme as the solution for writing unit tests with code coverage support.
  • Yarn as the package manager.

Who's the Starter for?

This starter is for those who with basic knowledge of React and have the need for building a server-side app. In other words, it's not for a newbie. If you're new to React or you don't need a server-side rendering app, I'd recommend you give create-react-app a try.

Requirements

Looking for Docker?

You can find Docker support version on this branch.

Getting Started

1. You can start by cloning the repository on your local machine by running:

git clone https://github.com/wellyshen/react-cool-starter.git
cd react-cool-starter

2. Install all of the dependencies:

yarn

3. Start to run it:

yarn build  # Building bundle
yarn start  # Running production server

Now the app should be running at http://localhost:8080/

Note: You can change the port that you want from ./package.json.

Script Commands

I use cross-env to set and use environment variables across platforms. All of the scripts are listed as following:

yarn <script> Description
dev Run your app on the development server at localhost:3000. HMR will be enabled.
start Run your app on the production server only at localhost:8080.
build Delete the previous bundled files and bundle it to ./public/assets.
analyze Visualize the contents of all your bundles.
type-check Run type checking for .tsx? files.
type-check:watch Run an interactive type checking watcher .
lint Lint all .tsx?, .jsx? and .scss files.
lint:code Lint all .tsx? and .jsx? files (With --fix to auto fix eslint errors).
lint:style Lint all .scss files (With --fix to auto fix stylelint errors).
test Run testing.
test:cov Run testing with code coverage reports.
test:watch Run an interactive test watcher.
test:update Update jest snapshot.
clean Delete the client/server bundled stuff and the coverage report.
clean:build Delete the ./public/assets folder to clean the client bundled files.
clean:cov Delete the ./coverage folder to clean the code coverage report.

App Structure

Here is the structure of the app, which serves as generally accepted guidelines and patterns for building scalable apps.

.
β”œβ”€β”€ public                          # Express server static path/Webpack bundled output
β”‚   └── favicon.ico                 # Favicon is placed in the same path with the main HTML page
β”œβ”€β”€ src                             # App source code
β”‚   β”œβ”€β”€ config                      # App configuration settings
β”‚   β”‚   β”œβ”€β”€ default.ts              # Default settings
β”‚   β”‚   β”œβ”€β”€ index.ts                # Configuration entry point
β”‚   β”‚   └── prod.ts                 # Production settings (overrides the default settings)
β”‚   β”œβ”€β”€ components                  # Reusable components (including scss/testing files)
β”‚   β”œβ”€β”€ pages                       # Page components (including scss/testing files)
β”‚   β”œβ”€β”€ app                         # App root component (including scss/testing files)
β”‚   β”œβ”€β”€ actions                     # Redux actions (including testing files)
β”‚   β”œβ”€β”€ reducers                    # Redux reducers (including testing files)
β”‚   β”œβ”€β”€ utils                       # App-wide utils (e.g. configure Redux store, HTML template etc.)
β”‚   β”œβ”€β”€ static                      # Static assets (e.g. images, fonts etc.)
β”‚   β”œβ”€β”€ theme                       # App-wide style and vendor CSS framework
β”‚   β”œβ”€β”€ types                       # Typescript type declarations for redux and global
β”‚   β”œβ”€β”€ client.tsx                  # App bootstrap and rendering (webpack entry)
β”‚   β”œβ”€β”€ routes.tsx                  # Routes configuration for both client and server side
β”‚   └── server.tsx                  # Express server (with webpack dev/hot middlewares)
β”œβ”€β”€ tools                           # Project related configurations (testing/build etc.)
β”‚   β”œβ”€β”€ jest                        # Jest CSS modules and assets mocks settings
β”‚   β”œβ”€β”€ webpack                     # Webpack settings
β”‚   β”‚   β”œβ”€β”€ config.babel.js         # Webpack configuration
β”‚   β”‚   └── hooks.js                # Assets require hooks
β”œβ”€β”€ index.ts                        # App entry point
└── postcss.config.js               # PostCSS configuration

Server-Side Security and Performance

Concerning the security and performance of Express in production, I already setup some middleware for you:

  • helmet - Helps secure Express server with various HTTP headers.
  • hpp - Express middleware to protect against HTTP Parameter Pollution attacks.
  • compression - Gzip compression support for speeding up Express server responses.

Note: It's just a basic protected mechanism for your app, you can see the security best practices for more advanced configuration.

Setup Redux DevTools Extension

The Redux Devtools Extension let us wire up our Redux app to a time-traveling debugger. It's enabled in development only. You can follow these installation guides to use it:

For Chrome

For Firefox

For Electron

For other browsers and non-browser environment

Overview

Functional Components and Hooks

React v16.8 introduced a series of Hooks, which let you use state and other React features without writing a class. In the starter boilerplate, you can see how I leverage the benefit of functional components + hook APIs to write a demo with clean code.

Adding Routes

This starter use React Router library to manage our routes. For the purpose of SSR with data pre-fetched, I put the routes in a centralized Route Config. You can setup your routes in ./src/routes.tsx. For example:

import RouteComponent from './pages/RouteComponent';

// ...

export default [
  {
    // Define your route path
    path: '/top-path',
    // If the route matches the location.pathname exactly or not (used for index route usually)
    exact: true,
    // Add your route component here
    component: RouteComponent,
    // Add your sub route component here
    routes: [
      {
        path: '/top-path/sub-path',
        component: SubRouteComponent
      }
    ]
    // ...
  }
  // Setup other route components...
];

Data Fetching from Server-side

Just write Redux actions and stores as normal (read the Redux document if you are new). The starter using axios as the data fetcher, it's quite simple and easy to use. If the action creator is asynchronous then it will return a Promise (or a Promise.all) in the inner function.

Register the action(s) in ./src/routes.tsx, which have to be called from server-side:

// ...

export default [
  {
    path: '/top-path',
    exact: true,
    component: RouteComponent,
    // Actions in the loadData function will be fetched from server-side
    loadData: () => [
      myReduxAction()
      // Add other pre-fetched actions here
    ]
  }
  // ...
];

The action(s) will be dispatched through ./src/server.tsx on server-side:

// ...

app.get('*', (req, res) => {
  // ...

  // Here's the method for loading data from server-side
  const loadBranchData = () => {
    const branch = matchRoutes(routes, req.path);

    const promises = branch.map(({ route, match }) => {
      if (route.loadData) {
        return Promise.all(
          route
            .loadData({ params: match.params, getState: store.getState })
            .map(item => store.dispatch(item))
        );
      }

      return Promise.resolve(null);
    });

    return Promise.all(promises);
  };

  // ...
});

// ...

In client-side, don't forget to invoke the action(s) in componentDidMount or useEffect hook. This ensures that if the component is reached on the client, then the same actions will be invoked. It's up to the action(s) to figure out if fetches for data need to be made or not:

// If you use React class component

componentDidMount() {
  // Invoke your redux action(s) for client rendering
  this.props.myReduxAction();
}

// If you use functional component

useEffect(() => {
  myReduxAction();
}, [])

Code Splitting

One great feature of the web is that you don’t have to make your visitors download the entire app before they can use it. You can think of code splitting as incrementally downloading the app. It divides your code into small pieces called β€œchunks” to reduce the size of bundle loaded by user. Reducing the size of a chunk makes it load and run faster.

To accomplish this, I integrate loadable-components into this starter. The reason I choose the library is because of its design philosophy of SSR. It works seamless with the starter rather than others. Let’s see how we split our app by route:

I use the following folder/file structure:

 |- pages
    |- AsyncRouteComponent
       |- index.js             // Wrap the route component as async component
       |- RouteComponent.tsx   // The route component

The index.js will be:

import loadable from '@loadable/component';

import { Error, Loading } from '../../components';

// Import your async route component
const AsyncComponent = loadable(() => import('./AsyncComponent'), {
  // Loading component will be displayed when the component is being loaded
  fallback: <Loading />
});

export default props => (
  // Wrap an <ErrorBoundary /> to catch the error of <AsyncComponent /> (via "componentDidCatch()" life cycle)
  <ErrorBoundary>
    <AsyncComponent {...props} />
  </ErrorBoundary>
);

Then you can setup the route as usual.

Note: I just show a general case route-based splitting, however you can even split your app by component-based depends on your need. For more advanced configuration you can refer to the document of loadable-components.

Managing Title, Meta, Styles and Scripts

The ./src/app/index.tsx (app root component) defines the base title and meta in a <Helmet {...config.app} /> component. Any sub-component can override/add properties (supports meta, link, script, style tags and html attributes). See the react-helmet document for more info.

App config

You can store app settings under ./src/config. By default the default.ts will be loaded. If the process.env.NODE_ENV matches to production, the prod.ts will be used instead, and it inherits the data info from default.ts.

You can access the correct config with:

import config from './config';

Styles

The starter supports CSS, SASS and CSS modules is enabled by default. I use PostCSS plugin to parse CSS and add autoprefixer to your stylesheet. You can access your stylesheet with two ways.

With CSS modules:

import styles from './styles.scss';

// ...

return (
  <div className={styles.myClass}>
    {/* The className matches one of CSS classes in your SCSS file */}
    <Helmet title="My title" />
    {this.renderContent()}
  </div>
);

Without CSS modules (you need to turn off CSS modules from ./tools/webpack/config.babel.js):

import './styles.scss';

// ...

return (
  <div className="myClass">
    {/* Use the CSS class as normal */}
    <Helmet title="My title" />
    {this.renderContent()}
  </div>
);

By the way, if you want to use vendor CSS frameworks or global styles, just import it through the ./src/app/index.tsx file (app root component). For example:

import '../../theme/normalize.css'; // Import a vendor stylesheet here
import styles from './styles.scss'; // Import your based stylesheet here

// ...

export default routes => {
  // ...
};

Image and Font

It's super easy to render the image and font both on client and server, the usage would be like below.

Using image:

// Require an image
<img src={require('./assets/logo.svg')} alt="Logo" role="presentation" />

Using font-awesome:

// With CSS modules
import styles from './styles.scss';

// ...

return (
  <div>
    <div>
      <i className={styles.iconUser} /> Welly
    </div>
  </div>
);

// Without CSS modules
import './font-awesome.css';

// ...

return (
  <div>
    <div>
      <i className="fa fa-icon" /> Welly
    </div>
  </div>
);

For using CSS modules, you have to set the proper font path in your scss/sass file:

$fa-font-path:"../node_modules/font-awesome/fonts";
@import "../node_modules/font-awesome/scss/font-awesome";

.icon-user {
  @extend .fa;
  @extend .fa-user;
}

Boost App Performance

In this starter, you can see I use React.PureComponent and React.memo to demostrate the basic performance optimizing for React app. The two APIs are used in different ways.

  • React.PureComponent is used for React class components. It can do shallow prop and state comparison for a performance boost:
import React, { PureComponent } from 'react';

// ...

class MyComponent extends PureComponent {
  // Only re-renders if props change
  // ...
}
  • React.memo is used for functional components. It plays the same role as React.PureComponent:
import React, { memo } from 'react';

// ...

const MyComponent = memo(props => {
  // Only re-renders if props change
  // ...
});
  • In addition, you can also use useMemo to avoid expensive calculations on every render:
import React, { useMemo } from 'react';

// ...

const MyComponent = props => {
  // ...

  return (
    <div>
      {/* Only re-renders if "a" change */}
      {useMemo(
        () => (
          <SomeComponent someProp={a} />
        ),
        [a]
      )}
    </div>
  );
};

For more performance optimizing techniques. Please see the Optimizing Performance topic.

Typescript

Typescript is a typed super-set of JavaScript. It's getting more and more popular in the Front-end world. And being widely used by many libraries. If you are new to Typescript, you can check out its document here.

Typescript has been integrated with our application to bring the following benefits:

  • Type safety for components, reducers, state and actions.
  • Many IDEs support the hints of Typescript, which give us a superior developer experience.
  • Easy refactoring of typed code.
  • In general, more types less bugs. Read this article to know more.

Code and Style Lint

ESLint (With Airbnb config), typescript-eslint, StyleLint, Prettier and lint-staged are integrated into this starter to maintain a consistent code style and give you a elegant code formatting. You can configure your lint rules through ./package.json file.

Unit Tests

This starter use Jest as the testing engine. It runs in a Node environment, so you won't have access to the DOM. In addition, Jest support the feature of snapshot testing, which is very powerful for testing React component. Give it a try, you'll be impressed.

I also use enzyme as the testing utility for React, which makes it easier to assert, manipulate, and traverse your React Components' output. The unit tests focus on three parts as below:

  • Components
  • Actions
  • Reducers

By the way, Jest built-in code coverage reports, the report files are generated in ./coverage folder. You can configure ./package.json to define which files that you want to cover. For example:

{
  // ...
  "jest": {
    "collectCoverageFrom": [
      "src/pages/**/*.tsx",     // Define the files, which want to be covered
      "!src/pages/index.ts"     // The files will be ignored by code coverage
    ],
    // Other configurations
  },
  // ...
}

You can also use istanbul's ignore hints to specify specific lines of code in a Javascript file to skip code coverage.

How to Deploy

To deploy you app to cloud service (e.g. AWS, GCP), you can follow the instructions below.

  1. Build then install production dependencies:
yarn build                  # Building bundle
rm -rf node_modules         # After building remove node modules
yarn install --production   # Then install dependencies only
  1. Pack necessary folders/files to your Node.js server:
  • βœ… node_modules
  • βœ… public
  • βœ… src
  • βœ… tools/webpack
  • βœ… index.ts
  • βœ… postcss.config.js
  • βœ… package.json
  • βœ… tsconfig.json
  1. Run your app:
yarn start

Ideally, the above steps can be integrated into your CI. I recommend you to pack the yarn.lock for yarn installation by CI.

Troubleshooting

  • If app crash due to the error: Invariant Violation: loadable: SSR requires "@loadable/babel-plugin", please install it (refer to this issue). To solve that, you must use .js extension for code-splitting files (e.g. src/Home/index.js).

  • If you encounter the markup mismatches error (it's a React universal issue, which usually occurs due to the non-synchronized rendering result between client and server), you can do:

    • Restart the server to solve it.
    • Or for v16.1.0 up, you can use suppressHydrationWarning attribute for intentional client/server text mismatches (#11126).
  • If you are on windows and encounter the following error: Expected linebreaks to be 'LF' but found 'CRLF' linebreak-style. The following rule must be added to ./package.json.

"linebreak-style": 0

So it will look like:

// ...
"rules": {
  "linebreak-style": 0,
  "global-require": 0,
  // Other rules

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Welly

πŸ’» πŸ“– 🚧

Microflow

🌍

Jason Bacchetta

πŸ”§

Nikita Balabaev

πŸ’»

James Sherry

πŸš‡ πŸ›

Zack Pelz

🌍

apapacy

πŸ’»

martin2786

πŸ“–

iamacup

πŸ”§

Maxim

πŸ”§

Benny Neugebauer

🌍

A. S. Lapkov

πŸ’»

Alireza Valizade

πŸ’»

Grant Millar

πŸ› πŸ’»

Bart

πŸ›

Morteza Tourani

πŸ’»

Tom Kiernan

🌍

Nathan KREMER

πŸ’»

Amer Lotfi Orimi

πŸ”§

Muhammad Umar

πŸ’»

Denny Vuong

πŸ“– πŸ’»

Matt Carlotta

πŸ’»

This project follows the all-contributors specification. Contributions of any kind welcome!

react-cool-starter's People

Contributors

alirezavalizade avatar allcontributors[bot] avatar amerllica avatar apapacy avatar aslapkov avatar bennycode avatar bjvda avatar dependabot[bot] avatar forwardomg avatar greenkeeper[bot] avatar iamacup avatar jabacchetta avatar jmsherry avatar martin2786 avatar mattcarlotta avatar mortezat avatar nimahkh avatar rid avatar tomkiernan120 avatar w3debugger avatar wellykkstream avatar wellyshen avatar xd3coder avatar zace2 avatar

Watchers

 avatar

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.