33 | );
34 | }
35 | }
36 |
37 | export default CounterComponent;
38 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2017 Bhargav Ponnapalli
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/src/client/containers/ServerError/index.js:
--------------------------------------------------------------------------------
1 | import React, { Component } from "react";
2 | import styled from "styled-components";
3 | import PropTypes from "prop-types";
4 |
5 | const Heading = styled.h2`font-size: 2em;`;
6 | const Status = styled.h1`
7 | font-size: 3em;
8 | color: gold;
9 | `;
10 | const Message = styled.p`
11 | font-style: italic;
12 | max-width: 80%;
13 | margin: 1em auto;
14 | `;
15 |
16 | const Banner = styled.img`
17 | height: auto;
18 | width: 300px;
19 | max-width: 80%;
20 | margin: auto;
21 | `;
22 |
23 | class ServerError extends Component {
24 | static propTypes = {
25 | location: PropTypes.object.isRequired
26 | };
27 | render() {
28 | const { state = {} } = this.props.location;
29 | const { status = 500 } = state;
30 | return (
31 |
32 |
33 | {status}
34 |
35 | Oops!
36 |
37 | We messed up! Our team of monkeys are on it right now!
38 |
39 |
40 |
15 | About
16 |
17 | Leo nullam arcu scelerisque hendrerit consectetur cum ullamcorper a
18 | hac erat turpis ac a hac porttitor suspendisse et a ac tristique. A
19 | eros neque integer fermentum pulvinar ut ullamcorper himenaeos a
20 | taciti commodo a nam nibh vel nunc mi praesent quam duis quam cursus
21 | sociosqu. Dictumst at eros cursus a sed mus cubilia adipiscing
22 | parturient ante hendrerit in litora felis leo. Lacinia vestibulum
23 | adipiscing vehicula etiam tortor maecenas felis vestibulum adipiscing
24 | rhoncus a suspendisse leo scelerisque ultrices elit parturient.
25 |
26 |
27 | Lorem mi tempus turpis quis adipiscing ac ipsum dui convallis dui
28 | class hendrerit ante neque dignissim taciti vestibulum libero
29 | tincidunt. Quis ligula suscipit non euismod ridiculus rhoncus
30 | vestibulum nec consectetur scelerisque imperdiet commodo diam erat
31 | orci dictum sapien malesuada per senectus a adipiscing. At nunc a
32 | vestibulum id adipiscing praesent tristique purus in est a parturient
33 | ullamcorper hac condimentum suspendisse a eget praesent cum in
34 | adipiscing natoque ullamcorper praesent non. Mus a vestibulum
35 | parturient eget nulla duis nunc fusce ipsum eu dapibus vivamus quam
36 | tempus a vestibulum platea maecenas sociis amet facilisis adipiscing
37 | consectetur ullamcorper neque dui nisl. A sem magna litora ad a
38 | condimentum scelerisque dui sociosqu ornare id a posuere dictum ad
39 | habitant netus a pretium nisi a torquent a vestibulum. Condimentum
40 | commodo duis rhoncus commodo a aptent sit ante urna in scelerisque
41 | parturient natoque augue ultricies diam eu ac.
42 |
43 |
44 | );
45 | }
46 | }
47 |
48 | export default About;
49 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
6 |
7 | ## Our Standards
8 |
9 | Examples of behavior that contributes to creating a positive environment include:
10 |
11 | * Using welcoming and inclusive language
12 | * Being respectful of differing viewpoints and experiences
13 | * Gracefully accepting constructive criticism
14 | * Focusing on what is best for the community
15 | * Showing empathy towards other community members
16 |
17 | Examples of unacceptable behavior by participants include:
18 |
19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances
20 | * Trolling, insulting/derogatory comments, and personal or political attacks
21 | * Public or private harassment
22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission
23 | * Other conduct which could reasonably be considered inappropriate in a professional setting
24 |
25 | ## Our Responsibilities
26 |
27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
28 |
29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
30 |
31 | ## Scope
32 |
33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
34 |
35 | ## Enforcement
36 |
37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at bhargavponnapalli.5@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
38 |
39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
40 |
41 | ## Attribution
42 |
43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
44 |
45 | [homepage]: http://contributor-covenant.org
46 | [version]: http://contributor-covenant.org/version/1/4/
47 |
--------------------------------------------------------------------------------
/webpack.config.babel.js:
--------------------------------------------------------------------------------
1 | import webpack from "webpack";
2 | import path from "path";
3 | import HtmlWebpackPugPlugin from "html-webpack-pug-plugin";
4 | import HtmlWebpackPlugin from "html-webpack-plugin";
5 | import CopyWebpackPlugin from "copy-webpack-plugin";
6 | import UglifyJSPlugin from "uglifyjs-webpack-plugin";
7 | import SWPrecacheWebpackPlugin from "sw-precache-webpack-plugin";
8 |
9 | const env = {
10 | prod: process.env.NODE_ENV !== "development",
11 | dev: process.env.NODE_ENV === "development"
12 | };
13 | // utilities to add features based on env
14 | const addEntity = (add, entity) => {
15 | return add ? entity : undefined;
16 | };
17 | const ifProd = entity => addEntity(env.prod, entity);
18 | const ifDev = entity => addEntity(env.dev, entity);
19 | const removeEmpty = array => array.filter(i => !!i);
20 |
21 | const PUBLIC_PATH = env.prod ? "/" : "http://localhost:8888/";
22 |
23 | // set contentBase
24 | const contentBase = env.prod
25 | ? __dirname + "/tmp/static"
26 | : __dirname + "/src/client";
27 |
28 | export default {
29 | mode: process.env.NODE_ENV,
30 | entry: removeEmpty([
31 | ifDev("react-hot-loader/patch"),
32 | ifDev("webpack-hot-middleware/client"),
33 | path.join(__dirname, "src/client/index.js")
34 | ]),
35 | output: {
36 | path: path.join(__dirname, "tmp/static"),
37 | filename: env.prod ? "[name].[chunkhash].js" : "[name].bundle.js"
38 | },
39 | devtool: env.dev ? "eval-source-map" : "source-map",
40 | module: {
41 | rules: [
42 | {
43 | test: /\.js$/,
44 | exclude: /node_modules/,
45 | use: ["babel-loader"],
46 | include: path.join(__dirname, "./src/client")
47 | }
48 | ]
49 | },
50 | plugins: removeEmpty([
51 | ifDev(new webpack.HotModuleReplacementPlugin()),
52 | ifProd(
53 | new HtmlWebpackPlugin({
54 | title: "Summer",
55 | filename: "templates/index.pug",
56 | template: path.join(__dirname, "src/server/templates/index.prod.pug")
57 | })
58 | ),
59 | ifProd(new HtmlWebpackPugPlugin()),
60 | ifProd(
61 | new CopyWebpackPlugin([
62 | {
63 | from: "static"
64 | }
65 | ])
66 | ),
67 | ifProd(
68 | new UglifyJSPlugin({
69 | sourceMap: true
70 | })
71 | ),
72 | new SWPrecacheWebpackPlugin({
73 | cacheId: "react-universal-starter",
74 | dontCacheBustUrlsMatching: /\.\w{8}\./,
75 | filename: "service-worker.js",
76 | minify: true,
77 | navigateFallback: PUBLIC_PATH + "index.html",
78 | staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/]
79 | })
80 | ]),
81 | optimization: {
82 | occurrenceOrder: env.prod ? true : false,
83 | splitChunks: {
84 | cacheGroups: {
85 | commons: {
86 | chunks: "initial",
87 | minChunks: 2,
88 | maxInitialRequests: 5, // The default limit is too small to showcase the effect
89 | minSize: 0 // This is example is too small to create commons chunks
90 | },
91 | vendor: {
92 | test: /node_modules/,
93 | chunks: "initial",
94 | name: "vendor",
95 | priority: 10,
96 | enforce: true
97 | }
98 | }
99 | }
100 | }
101 | };
102 |
--------------------------------------------------------------------------------
/src/server/index.js:
--------------------------------------------------------------------------------
1 | import path from "path";
2 | import fs from "fs";
3 | import React from "react";
4 | import { renderToString } from "react-dom/server";
5 | import express from "express";
6 | import webpack from "webpack";
7 | import webpackDevMiddleware from "webpack-dev-middleware";
8 | import webpackHotMiddleware from "webpack-hot-middleware";
9 | import { StaticRouter as Router } from "react-router";
10 | import { matchPath } from "react-router-dom";
11 | import { Provider } from "react-redux";
12 | import { ServerStyleSheet } from "styled-components";
13 | import App, { loadData } from "../client/app";
14 | import createStore from "../client/store/createStore";
15 | import rootReducer from "../client/reducers";
16 |
17 | // Environment variables
18 | const isDevelopment = process.env.NODE_ENV === "development";
19 |
20 | // Create app
21 | const app = express();
22 |
23 | //set port
24 | const port = process.env.PORT || 8888;
25 |
26 | // set statics
27 | const staticPath = path.join(__dirname, "../../", "static");
28 |
29 | if (isDevelopment) {
30 | const webpackConfig = require("../../webpack.config.babel.js").default;
31 | const compiler = webpack(webpackConfig);
32 | app.use(
33 | webpackDevMiddleware(compiler, {
34 | logLevel: "warn",
35 | publicPath: webpackConfig.output.publicPath,
36 | historyApiFallback: true
37 | })
38 | );
39 | app.use(
40 | webpackHotMiddleware(compiler, {
41 | log: console.log,
42 | heartbeat: 4 * 1000
43 | })
44 | );
45 | }
46 |
47 | app.use(express.static(staticPath));
48 |
49 | // set view engine
50 | app.set("view engine", "pug");
51 | // set views directory
52 | if (isDevelopment) {
53 | app.set("views", path.join(__dirname, "templates"));
54 | } else {
55 | app.set("views", path.join(__dirname, "../../", "static/templates"));
56 | }
57 |
58 | //Root html template
59 | let indexTemplate = "index.dev.pug";
60 | if (!isDevelopment) {
61 | indexTemplate = "index";
62 | }
63 |
64 | const context = {};
65 |
66 | function render(req, res, err) {
67 | // setting counter initial value to 5
68 | const store = createStore(rootReducer, {
69 | counter: 5
70 | });
71 | const promises = [];
72 | loadData.some(route => {
73 | // use `matchPath` here
74 | const match = matchPath(req.path, route);
75 | if (match) {
76 | if (route.loadData) {
77 | promises.push(route.loadData(store, match, req.url));
78 | }
79 | }
80 | return match;
81 | });
82 | Promise.all(promises).then(() => {
83 | const sheet = new ServerStyleSheet();
84 | let html = renderToString(
85 | sheet.collectStyles(
86 |
87 |
88 |
89 |
90 |
91 | )
92 | );
93 |
94 | html += `
95 |
98 | `;
99 | const styleTags = sheet.getStyleTags();
100 | // This renders html as well as a concatenated string list of style tags
101 | res.render(indexTemplate, {
102 | content: html,
103 | styles: styleTags
104 | });
105 | });
106 | }
107 |
108 | // add routes
109 | app.get("/throw", (req, res, next) => {
110 | next(new Error("we messed up"));
111 | });
112 |
113 | app.get("*", (req, res) => {
114 | render(req, res);
115 | });
116 |
117 | if (isDevelopment) {
118 | app.use(function(err, req, res, next) {
119 | res.status(err.status || 500);
120 | res.redirect("/500");
121 | });
122 | }
123 |
124 | // start app
125 | app.listen(port, () => {
126 | console.info(
127 | `🌎 Listening on port ${port} in ${process.env.NODE_ENV} mode on Node ${
128 | process.version
129 | }.`
130 | );
131 | if (isDevelopment) {
132 | console.info(`Open http://localhost:8888`);
133 | }
134 | });
135 |
--------------------------------------------------------------------------------
/src/client/registerServiceWorker.js:
--------------------------------------------------------------------------------
1 | // In production, we register a service worker to serve assets from local cache.
2 |
3 | // This lets the app load faster on subsequent visits in production, and gives
4 | // it offline capabilities. However, it also means that developers (and users)
5 | // will only see deployed updates on the "N+1" visit to a page, since previously
6 | // cached resources are updated in the background.
7 |
8 | // To learn more about the benefits of this model, read https://goo.gl/KwvDNy.
9 | // This link also includes instructions on opting out of this behavior.
10 |
11 | const isLocalhost = Boolean(
12 | window.location.hostname === "localhost" ||
13 | // [::1] is the IPv6 localhost address.
14 | window.location.hostname === "[::1]" ||
15 | // 127.0.0.1/8 is considered localhost for IPv4.
16 | window.location.hostname.match(
17 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
18 | )
19 | );
20 |
21 | export default function register() {
22 | if (process.env.NODE_ENV === "production" && "serviceWorker" in navigator) {
23 | window.addEventListener("load", () => {
24 | const swUrl = `/service-worker.js`;
25 |
26 | if (!isLocalhost) {
27 | // Is not local host. Just register service worker
28 | registerValidSW(swUrl);
29 | } else {
30 | // This is running on localhost. Lets check if a service worker still exists or not.
31 | checkValidServiceWorker(swUrl);
32 | }
33 | });
34 | }
35 | }
36 |
37 | function registerValidSW(swUrl) {
38 | navigator.serviceWorker
39 | .register(swUrl)
40 | .then(registration => {
41 | registration.onupdatefound = () => {
42 | const installingWorker = registration.installing;
43 | installingWorker.onstatechange = () => {
44 | if (installingWorker.state === "installed") {
45 | if (navigator.serviceWorker.controller) {
46 | // At this point, the old content will have been purged and
47 | // the fresh content will have been added to the cache.
48 | // It's the perfect time to display a "New content is
49 | // available; please refresh." message in your web app.
50 | console.log("New content is available; please refresh.");
51 | } else {
52 | // At this point, everything has been precached.
53 | // It's the perfect time to display a
54 | // "Content is cached for offline use." message.
55 | console.log("Content is cached for offline use.");
56 | }
57 | }
58 | };
59 | };
60 | })
61 | .catch(error => {
62 | console.error("Error during service worker registration:", error);
63 | });
64 | }
65 |
66 | function checkValidServiceWorker(swUrl) {
67 | // Check if the service worker can be found. If it can't reload the page.
68 | fetch(swUrl)
69 | .then(response => {
70 | // Ensure service worker exists, and that we really are getting a JS file.
71 | if (
72 | response.status === 404 ||
73 | response.headers.get("content-type").indexOf("javascript") === -1
74 | ) {
75 | // No service worker found. Probably a different app. Reload the page.
76 | navigator.serviceWorker.ready.then(registration => {
77 | registration.unregister().then(() => {
78 | window.location.reload();
79 | });
80 | });
81 | } else {
82 | // Service worker found. Proceed as normal.
83 | registerValidSW(swUrl);
84 | }
85 | })
86 | .catch(() => {
87 | console.log(
88 | "No internet connection found. App is running in offline mode."
89 | );
90 | });
91 | }
92 |
93 | export function unregister() {
94 | if ("serviceWorker" in navigator) {
95 | navigator.serviceWorker.ready.then(registration => {
96 | registration.unregister();
97 | });
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | When contributing to this repository, please first discuss the change you wish to make via issue,
4 | email, or any other method with the owners of this repository before making a change.
5 |
6 | Please note we have a code of conduct, please follow it in all your interactions with the project.
7 |
8 | ## Pull Request Process
9 |
10 | 1. Ensure any install or build dependencies are removed before the end of the layer when doing a
11 | build.
12 | 2. Update the README.md with details of changes to the interface, this includes new environment
13 | variables, exposed ports, useful file locations and container parameters.
14 | 3. Increase the version numbers in any examples files and the README.md to the new version that this
15 | Pull Request would represent. The versioning scheme we use is [SemVer](http://semver.org/).
16 | 4. You may merge the Pull Request in once you have the sign-off of two other developers, or if you
17 | do not have permission to do that, you may request the second reviewer to merge it for you.
18 |
19 | ## Code of Conduct
20 |
21 | ### Our Pledge
22 |
23 | In the interest of fostering an open and welcoming environment, we as
24 | contributors and maintainers pledge to making participation in our project and
25 | our community a harassment-free experience for everyone, regardless of age, body
26 | size, disability, ethnicity, gender identity and expression, level of experience,
27 | nationality, personal appearance, race, religion, or sexual identity and
28 | orientation.
29 |
30 | ### Our Standards
31 |
32 | Examples of behavior that contributes to creating a positive environment
33 | include:
34 |
35 | * Using welcoming and inclusive language
36 | * Being respectful of differing viewpoints and experiences
37 | * Gracefully accepting constructive criticism
38 | * Focusing on what is best for the community
39 | * Showing empathy towards other community members
40 |
41 | Examples of unacceptable behavior by participants include:
42 |
43 | * The use of sexualized language or imagery and unwelcome sexual attention or
44 | advances
45 | * Trolling, insulting/derogatory comments, and personal or political attacks
46 | * Public or private harassment
47 | * Publishing others' private information, such as a physical or electronic
48 | address, without explicit permission
49 | * Other conduct which could reasonably be considered inappropriate in a
50 | professional setting
51 |
52 | ### Our Responsibilities
53 |
54 | Project maintainers are responsible for clarifying the standards of acceptable
55 | behavior and are expected to take appropriate and fair corrective action in
56 | response to any instances of unacceptable behavior.
57 |
58 | Project maintainers have the right and responsibility to remove, edit, or
59 | reject comments, commits, code, wiki edits, issues, and other contributions
60 | that are not aligned to this Code of Conduct, or to ban temporarily or
61 | permanently any contributor for other behaviors that they deem inappropriate,
62 | threatening, offensive, or harmful.
63 |
64 | ### Scope
65 |
66 | This Code of Conduct applies both within project spaces and in public spaces
67 | when an individual is representing the project or its community. Examples of
68 | representing a project or community include using an official project e-mail
69 | address, posting via an official social media account, or acting as an appointed
70 | representative at an online or offline event. Representation of a project may be
71 | further defined and clarified by project maintainers.
72 |
73 | ### Enforcement
74 |
75 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
76 | reported by contacting the project team at bhargavponnapalli.5@gmail.com. All
77 | complaints will be reviewed and investigated and will result in a response that
78 | is deemed necessary and appropriate to the circumstances. The project team is
79 | obligated to maintain confidentiality with regard to the reporter of an incident.
80 | Further details of specific enforcement policies may be posted separately.
81 |
82 | Project maintainers who do not follow or enforce the Code of Conduct in good
83 | faith may face temporary or permanent repercussions as determined by other
84 | members of the project's leadership.
85 |
86 | ### Attribution
87 |
88 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
89 | available at [http://contributor-covenant.org/version/1/4][version]
90 |
91 | [homepage]: http://contributor-covenant.org
92 | [version]: http://contributor-covenant.org/version/1/4/
93 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # react-universal-starter
2 | [](#contributors)
3 |
4 | The popular front end stack today is changing fast with React, react-router and webpack releasing newer versions. This is a starter app aimed to demonstrate how to integrate `babel@7`, `react@16`,`react-router@4` and `webpack@4`.
5 |
6 |
7 |
8 |
9 | ## [Link](https://react-universal-starter.now.sh)
10 |
11 | ## Screenshot
12 |
13 |
14 |
15 | ## Features
16 |
17 | This project comes with the following features
18 |
19 | - [x] React 16
20 | - [x] React Router 4
21 | - [x] Webpack 3
22 | - [x] Babel
23 | - [x] Server rendering
24 | - [x] Redux integration
25 | - [x] Dynamic imports
26 | - [x] Chunk splitting
27 | - [x] Styled components
28 | - [x] Nodemon
29 |
30 | ## Installation
31 |
32 | ```bash
33 | git clone git@github.com:imbhargav5/react-universal-starter.git
34 | cd react-universal-starter
35 | npm install
36 | ```
37 |
38 | ## Usage
39 |
40 | To run app in **dev** mode
41 |
42 | ```bash
43 | npm run dev
44 | ```
45 |
46 | The app should be running on `http://localhost:8888/`
47 |
48 |
49 |
50 | To run app in **production** mode
51 |
52 | ```bash
53 | npm build
54 | npm start
55 | ```
56 | The app should be running on `http://localhost:8888/`
57 |
58 |
59 |
60 | To clean and rebuild
61 |
62 | ```bash
63 | npm run build
64 | ```
65 |
66 | ## Available build scripts
67 |
68 | | `npm run