Merge pull request #1 from aleleba/PR-753737

Start up of the project.
This commit is contained in:
Alejandro Lembke Barrientos 2022-04-29 08:34:10 -06:00 committed by GitHub
commit 749060e1e5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
44 changed files with 28452 additions and 0 deletions

7
.babelrc Normal file
View File

@ -0,0 +1,7 @@
{
"presets": [
["@babel/preset-env", {"targets": {"node": "current"}}],
"@babel/preset-react",
"@babel/preset-typescript"
]
}

6
.env.example Normal file
View File

@ -0,0 +1,6 @@
#Environment
ENV= #Default production
#App Port
PORT= #Default 80
#PUBLIC URL
PUBLIC_URL= #Default /

10
.eslintignore Normal file
View File

@ -0,0 +1,10 @@
#Build
build
#Webpack
webpack.config.js
webpack.config.dev.js
#Server
/server/index.js
#Service Worker
service-worker.js
serviceWorkerRegistration.ts

52
.eslintrc.js Normal file
View File

@ -0,0 +1,52 @@
module.exports = {
'env': {
'browser': true,
'node': true,
'es2021': true
},
'extends': [
'eslint:recommended',
'plugin:react/recommended',
'plugin:@typescript-eslint/recommended'
],
'parser': '@typescript-eslint/parser',
'parserOptions': {
'ecmaFeatures': {
'jsx': true
},
'ecmaVersion': 'latest',
'sourceType': 'module'
},
'plugins': [
'react',
'@typescript-eslint'
],
'rules': {
'indent': [
'error',
'tab'
],
'linebreak-style': [
'error',
'unix'
],
'quotes': [
'error',
'single'
],
'semi': [
'error',
'always'
],
'eol-last': [
'error',
'always'
],
'@typescript-eslint/no-var-requires': 0,
},
'settings': {
'react': {
'version': 'detect',
}
}
};

6
.gitignore vendored Normal file
View File

@ -0,0 +1,6 @@
#node_modules ignore
node_modules
#.envs
.env
#builds
build

14
PRNameGenerator.ts Normal file
View File

@ -0,0 +1,14 @@
const PRName = function () {
let ID = '';
// let characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
const characters = '0123456789';
for ( let i = 0; i < 6; i++ ) {
ID += characters.charAt(Math.floor(Math.random() * 10));
}
return 'PR-'+ID;
};
console.log(PRName());
export default PRName;

73
README.md Normal file
View File

@ -0,0 +1,73 @@
# Create React SSR
This project aims to have a starter kit for creating a new React app with Server Side Rendering and tools that generally go along with it.
It is not a project like create-react-app, create-react-app is used as a starter kit that handles all your scripts underneath, this is a project for developers who want more control over their application.
Tech(Library or Framework) | Version |
--- | --- |
React (Render Library) | 18.0.0
Redux (Global State Management) | 4.1.2
React Router DOM (Routing) | 6.3.0
Jest (Testing) | 28.0.2
Typescript | 5.6.3
## Setup
To create a new project run in the terminal:
```
npx @aleleba/create-react-ssr app-name
```
Then run:
```
cd app-name
```
You will need to create a new .env file at the root of the project for global config.
This is an exaple of config.
```
#Environment
ENV=development #Default production
#App Port
PORT=3000 #Default 80
#PUBLIC URL
#PUBLIC_URL= #Default /
```
The default environment is production, the app port defauld is 80 and the defauld public url is "/".
### For Development
In the terminal run:
```
npm run start:dev
```
The ENV enviroment variable should be "development" and choose the port of your preference with the enviroment variable PORT.
You will find the root component on:
```
scr/frontend/components/App.tsx
```
You will find the Initial Component on:
```
scr/frontend/components/InitialComponent.tsx
```
The manage of the routes you should find on:
```
scr/routes
```
It is using "useRoutes" hook for working, more information for this here: (https://reactrouter.com/docs/en/v6/api#useroutes)
This will start the app in development mode, also it have Hot Reloading!
Enjoy coding!
### For Production
In the terminal run:
```
npm run build
```
It will create a build folder and run:
```
npm start
```
This will start the app.
## Cheers
Hope you enjoy this proyect! Sincerely Alejandro Lembke Barrientos.

29
bin/cli.js Normal file
View File

@ -0,0 +1,29 @@
#!/usr/bin/env node
const { execSync } = require('child_process');
const runCommand = command => {
try{
execSync(`${command}`, {stdio: 'inherit'});
} catch (e) {
console.error(`Failed to execute ${command}`, e);
return false;
}
return true;
}
const repoName = process.argv[2];
const gitCheckoutCommand = `git clone --depth 1 https://github.com/aleleba/create-react-ssr ${repoName}`;
const installDepsCommand = `cd ${repoName} && npm install`;
console.log(`Cloning the repository with name ${repoName}`);
const checkedOut = runCommand(gitCheckoutCommand);
if(!checkedOut) process.exit(-1);
console.log(`Installing dependencies for ${repoName}`);
const installedDeps = runCommand(installDepsCommand);
if(!installedDeps) process.exit(-1);
console.log("Congratulations! You are ready. Follow the following commands to start");
console.log(`cd ${repoName}`);
console.log('Create a .env file with ENV=development(defauld: production), PORT=3000 (default: 80), PUBLIC_URL=your_public_url(optional)(default: /)');
console.log(`Then you can run: npm start:dev`);

6
config/index.js Normal file
View File

@ -0,0 +1,6 @@
const config = {
env: process.env.ENV ? process.env.ENV : 'production',
port: process.env.PORT ? process.env.PORT : 80,
};
module.exports = { config: config };

4
custom.d.ts vendored Normal file
View File

@ -0,0 +1,4 @@
declare module "*.svg" {
const content: any;
export default content;
}

8
jest.config.js Normal file
View File

@ -0,0 +1,8 @@
module.exports = {
setupFilesAfterEnv: ['<rootDir>/setupTest.js'],
"testEnvironment": "jsdom",
moduleNameMapper: {
"\\.(jpg|ico|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/src/__mocks__/fileMock.js",
"\\.(css|sass|less)$": "identity-obj-proxy"
},
};

27107
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

107
package.json Normal file
View File

@ -0,0 +1,107 @@
{
"name": "@aleleba/create-react-ssr",
"version": "1.0.0",
"description": "Starter Kit of server side render of react",
"bin": "./bin/cli.js",
"main": "src/server/index",
"scripts": {
"start": "node build/server/app-server.js",
"start:dev": "ts-node src/server/index",
"build": "webpack-cli --config webpack.config.js",
"lint": "eslint ./ --ext .js --ext .ts --ext .jsx --ext .tsx",
"lint:fix": "eslint ./ --ext .js --ext .ts --ext .jsx --ext .tsx --fix",
"test": "jest",
"test:watch": "jest --watch"
},
"repository": {
"type": "git",
"url": "git+https://github.com/aleleba/create-react-ssr.git"
},
"keywords": [
"react",
"ssr"
],
"author": "Alejandro Lembke Barrientos",
"license": "MIT",
"bugs": {
"url": "https://github.com/aleleba/create-react-ssr/issues"
},
"homepage": "https://github.com/aleleba/create-react-ssr#readme",
"dependencies": {
"@babel/register": "^7.17.7",
"asset-require-hook": "^1.2.0",
"dotenv": "^16.0.0",
"express": "^4.17.3",
"helmet": "^5.0.2",
"ignore-styles": "^5.0.1",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"react-redux": "^8.0.0",
"react-router-dom": "^6.3.0",
"react-router-hash-link": "^2.4.3",
"redux": "^4.1.2",
"ts-node": "^10.7.0",
"webpack": "^5.72.0",
"webpack-manifest-plugin": "^5.0.0",
"workbox-background-sync": "^6.5.3",
"workbox-broadcast-update": "^6.5.3",
"workbox-cacheable-response": "^6.5.3",
"workbox-core": "^6.5.3",
"workbox-expiration": "^6.5.3",
"workbox-google-analytics": "^6.5.3",
"workbox-navigation-preload": "^6.5.3",
"workbox-precaching": "^6.5.3",
"workbox-range-requests": "^6.5.3",
"workbox-routing": "^6.5.3",
"workbox-strategies": "^6.5.3",
"workbox-streams": "^6.5.3"
},
"devDependencies": {
"@babel/core": "^7.17.9",
"@babel/preset-env": "^7.16.11",
"@babel/preset-react": "^7.16.7",
"@babel/preset-typescript": "^7.16.7",
"@pmmmwh/react-refresh-webpack-plugin": "^0.5.5",
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.1.1",
"@testing-library/user-event": "^14.1.1",
"@types/jest": "^27.4.1",
"@types/node": "^17.0.25",
"@types/react": "^18.0.5",
"@types/react-dom": "^18.0.0",
"@types/webpack-hot-middleware": "^2.25.6",
"@typescript-eslint/eslint-plugin": "^5.20.0",
"@typescript-eslint/parser": "^5.20.0",
"babel-jest": "^28.0.2",
"babel-loader": "^8.2.4",
"clean-webpack-plugin": "^4.0.0",
"compression-webpack-plugin": "^9.2.0",
"copy-webpack-plugin": "^10.2.4",
"css-loader": "^6.7.1",
"css-minimizer-webpack-plugin": "^3.4.1",
"eslint": "^8.13.0",
"eslint-plugin-react": "^7.29.4",
"eslint-webpack-plugin": "^3.1.1",
"file-loader": "^6.2.0",
"identity-obj-proxy": "^3.0.0",
"jest": "^28.0.2",
"jest-environment-jsdom": "^28.0.2",
"jest-fetch-mock": "^3.0.3",
"mini-css-extract-plugin": "^2.6.0",
"react-refresh": "^0.13.0",
"redux-devtools-extension": "^2.13.9",
"sass": "^1.50.0",
"sass-loader": "^12.6.0",
"style-loader": "^3.3.1",
"terser-webpack-plugin": "^5.3.1",
"typescript": "^4.6.3",
"url-loader": "^4.1.1",
"webpack-cli": "^4.9.2",
"webpack-dev-middleware": "^5.3.1",
"webpack-dev-server": "^4.8.1",
"webpack-hot-middleware": "^2.25.1",
"webpack-node-externals": "^3.0.0",
"workbox-webpack-plugin": "^6.5.3",
"workbox-window": "^6.5.3"
}
}

BIN
public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

BIN
public/logo192.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

BIN
public/logo512.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

25
public/manifest.json Normal file
View File

@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "React App SSR Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": "/",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

57
service-worker.js Normal file
View File

@ -0,0 +1,57 @@
// This service worker can be customized!
// See https://developers.google.com/web/tools/workbox/modules
// for the list of available Workbox modules, or add any other
// code you'd like.
// You can also remove this file if you'd prefer not to use a
// service worker, and the Workbox build step will be skipped.
import { clientsClaim } from 'workbox-core';
import { ExpirationPlugin } from 'workbox-expiration';
import { precacheAndRoute } from 'workbox-precaching'; //createHandlerBoundToURL
import { registerRoute } from 'workbox-routing';
import { StaleWhileRevalidate, NetworkFirst } from 'workbox-strategies';
clientsClaim();
// This allows the web app to trigger skipWaiting via
self.skipWaiting();
// Precache all of the assets generated by your build process.
// Their URLs are injected into the manifest variable below.
// This variable must be present somewhere in your service worker file,
// even if you decide not to use precaching. See https://cra.link/PWA
precacheAndRoute(self.__WB_MANIFEST);
// An example runtime caching route for requests that aren't handled by the
// precache, in this case same-origin .png requests like those from in public/
registerRoute(
// Add in any other file extensions or routing criteria as needed.
({ url }) => url.origin === self.location.origin && url.pathname.endsWith('.png'), // Customize this strategy as needed, e.g., by changing to CacheFirst.
new StaleWhileRevalidate({
cacheName: 'images',
plugins: [
// Ensure that once this runtime cache reaches a maximum size the
// least-recently used images are removed.
new ExpirationPlugin({ maxEntries: 50 }),
],
})
);
// Any other custom service worker logic can go here.
//Estrategy for Default. It should be at the end.
registerRoute(/^https?.*/, new NetworkFirst(), 'GET');
//Wait for Notification.
self.addEventListener('push', function (e) {
const data = e.data.json();
registration.showNotification(data.title, {
body: data.message,
icon: 'favicon.ico'
});
});
console.log('hello from service-worker.js the new one.');

View File

@ -0,0 +1,21 @@
import { Workbox } from 'workbox-window';
import packageJson from './package.json';
const serviceWorkerRegistration = () => {
if ('serviceWorker' in navigator) {
const wb = new Workbox('service-worker.js');
wb.addEventListener('installed', event => {
if(event.isUpdate){
if(confirm('New app update is avaible, Click Ok to refresh')){
window.location.reload();
};
console.log(`Se actualiza la app a version ${packageJson.version}`);
};
});
wb.register();
};
};
export default serviceWorkerRegistration;

20
setupTest.js Normal file
View File

@ -0,0 +1,20 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';
//import fetch Mock
import fetchMock from "jest-fetch-mock";
fetchMock.enableMocks();
//Fixing Pollyfill for react-slick
window.matchMedia =
window.matchMedia ||
function() {
return {
matches: false,
addListener: function() {},
removeListener: function() {}
};
};

View File

@ -0,0 +1,27 @@
import React from 'react';
import { Provider } from 'react-redux';
import { Router } from 'react-router-dom';
import { createMemoryHistory } from 'history';
import initialStateReducer from '../frontend/reducers/initialState';
import setStore from '../frontend/setStore';
const ProviderMock = ({ children, initialState }) => {
let initialStateMock = initialStateReducer
if(initialState !== undefined){
initialStateMock = initialState
}
const history = createMemoryHistory();
const store = setStore({ initialState: initialStateMock });
return(
<Provider store={store}>
<Router location={history.location} navigator={history}>
{children}
</Router>
</Provider>
)
}
export default ProviderMock;

View File

@ -0,0 +1 @@
module.exports = '';

View File

@ -0,0 +1,9 @@
import test, { TTest } from './testAction';
export type TAction = TTest
const actions = {
test
}
export default actions

View File

@ -0,0 +1,25 @@
export enum ActionTypesTest {
ChangeHello = 'CHANGE_HELLO'
}
export interface IChangeHello {
type: ActionTypesTest.ChangeHello
payload: IChangeHelloPayload
}
export interface IChangeHelloPayload {
hello: any | undefined
}
export type TTest = IChangeHello
const changeHello = (payload: string) => ({
type: 'CREATE_USER',
payload
})
const actions = {
changeHello
}
export default actions

View File

@ -0,0 +1,6 @@
import React from 'react';
import PrincipalRoutes from './PrincipalRoutes';
const App = () => <PrincipalRoutes />;
export default App;

View File

@ -0,0 +1,29 @@
.App
text-align: center
.App-logo
height: 40vmin
pointer-events: none
@media (prefers-reduced-motion: no-preference)
.App-logo
animation: App-logo-spin infinite 20s linear
.App-header
min-height: 100vh
display: flex
flex-direction: column
align-items: center
justify-content: center
font-size: calc(10px + 2vmin)
color: white
.App-link
color: #61dafb
@keyframes App-logo-spin
from
transform: rotate(0deg)
to
transform: rotate(360deg)

View File

@ -0,0 +1,26 @@
import React from 'react';
import logo from '../logo.svg';
import './InitialComponent.sass';
import { Link } from "react-router-dom";
const InitialComponent = () => (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/frontend/InitialComponent.jsx</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
<Link className="App-link" to="/other-component">Other Component</Link>
</header>
</div>
);
export default InitialComponent;

View File

@ -0,0 +1,18 @@
import React from 'react';
import logo from '../logo.svg';
import './InitialComponent.sass';
import { Link } from "react-router-dom";
const OtherComponent = () => (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit src/frontend/OtherComponent.jsx and save to reload.
</p>
<Link className="App-link" to="/">Initial Component</Link>
</header>
</div>
);
export default OtherComponent;

View File

@ -0,0 +1,11 @@
//Router
import { useRoutes } from 'react-router-dom';
//Routes
import routes from '../../routes';
const PrincipalRoutes = () => {
let element = useRoutes(routes);
return element;
};
export default PrincipalRoutes;

View File

@ -0,0 +1,23 @@
import React from 'react';
import { render } from '@testing-library/react';
import ProviderMock from '../../../__mocks__/ProviderMock';
import App from '../App';
describe('<App/> Component', () => {
beforeEach(() => {
fetch.resetMocks();
});
test('Should render root <App /> Component', async () => {
fetch.mockResponseOnce(JSON.stringify({
//First Data Fetch
data: 'data'
}));
render(
<ProviderMock>
<App />
</ProviderMock>
)
})
})

70
src/frontend/index.tsx Normal file
View File

@ -0,0 +1,70 @@
import React from 'react';
import { hydrateRoot } from 'react-dom/client';
// Router
import { BrowserRouter as Router } from 'react-router-dom';
// Redux
import { Provider } from 'react-redux';
import { IInitialState } from './reducers/index';
import setStore from './setStore';
import { config } from '../../config';
import './styles/global.sass';
import App from './components/App';
import serviceWorkerRegistration from '../../serviceWorkerRegistration';
declare global {
interface Window {
__PRELOADED_STATE__?: IInitialState;
}
}
declare global {
interface NodeModule {
hot?: IHot;
}
}
interface IHot {
accept: any
}
const { env } = config;
const preloadedState = window.__PRELOADED_STATE__;
const store = setStore({ initialState: preloadedState });
delete window.__PRELOADED_STATE__;
const container = document.getElementById('app')!;
// add "const root" to be able to rerender.
hydrateRoot(container,
<Provider store={store}>
<Router>
<App />
</Router>
</Provider>,
// Add this comment to update later app and remove warning
/* {
onRecoverableError: (error) => {
console.error("recoverable", error);
}
}, */
);
// Use root.render to update later the app
/* root.render(
<Provider store={store}>
<Router>
<App />
</Router>
</Provider>
); */
if((env) && (env === 'production')){
serviceWorkerRegistration();
}
if(module.hot){
module.hot.accept();
}

1
src/frontend/logo.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3"><g fill="#61DAFB"><path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/><circle cx="420.9" cy="296.5" r="45.7"/><path d="M520.5 78.1z"/></g></svg>

After

Width:  |  Height:  |  Size: 2.6 KiB

View File

@ -0,0 +1,14 @@
import { combineReducers } from 'redux';
import testReducer from './testReducer';
import { IChangeHelloPayload } from '../actions/testAction';
export interface IInitialState {
testReducer?: IChangeHelloPayload | undefined
}
const rootReducer = combineReducers({
// Here comes the reducers
testReducer
});
export default rootReducer;

View File

@ -0,0 +1,2 @@
const initialState = {};
export default initialState;

View File

@ -0,0 +1,20 @@
import { TAction } from '../actions';
const initialState = {
hello: 'world'
};
const testReducer = (state = initialState, action: TAction) => {
switch (action.type){
case 'CHANGE_HELLO': {
const newHello = action.payload.hello;
return {
hello: newHello
};
}
default:
return state;
}
};
export default testReducer;

27
src/frontend/setStore.ts Normal file
View File

@ -0,0 +1,27 @@
// Redux
import { createStore } from 'redux'; //, applyMiddleware
// import { Provider } from 'react-redux';
import { composeWithDevTools as composeWithDevToolsWeb } from 'redux-devtools-extension';
import { config } from '../../config';
import reducer, { IInitialState } from './reducers';
const { env } = config;
const composeEnhancers = composeWithDevToolsWeb({
// Specify here name, actionsBlacklist, actionsCreators and other options
});
const setStore = ({ initialState }: { initialState: IInitialState | undefined }) => {
const store = env === 'development' ? createStore(
reducer,
initialState,
composeEnhancers(),
) : createStore(
reducer,
initialState,
);
return store;
};
export default setStore;

View File

@ -0,0 +1,4 @@
$base-color: #282c34
body
background-color: $base-color

16
src/routes/index.js Normal file
View File

@ -0,0 +1,16 @@
import React from 'react';
import InitialComponent from '../frontend/components/InitialComponent';
import OtherComponent from '../frontend/components/OtherComponent';
const OTHER_COMPONENT = {
path: '/other-component',
element: <OtherComponent />
};
const INITIAL_COMPONENT = {
path: '/',
element: <InitialComponent />,
};
export default [ INITIAL_COMPONENT, OTHER_COMPONENT ];

View File

@ -0,0 +1,13 @@
import fs from 'fs';
const getHashManifest = () => {
try {
const baseUrl = __dirname.replace(/\/server(.*)/,'');
const fullURL = `${baseUrl}/assets/manifest-hash.json` ;
return JSON.parse(fs.readFileSync(fullURL));
}catch(err){
console.error(err);
}
};
export default getHashManifest;

44
src/server/index.js Normal file
View File

@ -0,0 +1,44 @@
require('dotenv').config();
require('ignore-styles');
//require('webpack-node-externals')();
require('@babel/register')({
'presets': [
['@babel/preset-env', {'targets': {'node': 'current'}}],
'@babel/preset-react',
'@babel/preset-typescript',
]
});
require('asset-require-hook')({
extensions: [
// images
'jpg',
'png',
'svg',
'gif',
'ico',
// videos
'mp4',
'avi',
// files
'pdf',
],
name: '/assets/media/[name].[ext]',
});
require('asset-require-hook')({
extensions: [
// typography
'ttf',
'otf',
'eot',
'woff',
'woff2',
],
name: '/assets/fonts/[name].[ext]',
});
require('./server');

122
src/server/server.js Normal file
View File

@ -0,0 +1,122 @@
//Dependencies of Server
import express from 'express';
import { config } from '../../config';
import webpack from 'webpack';
import helmet from 'helmet';
//Dependencies of HotReloading
import webpackConfig from '../../webpack.config.dev';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
//Dependencies of SSR
import React from 'react';
import { renderToString } from 'react-dom/server';
//Router
import { StaticRouter } from 'react-router-dom/server';
import routes from '../routes';
//Redux
import { Provider } from 'react-redux';
import setStore from '../frontend/setStore';
import initialState from '../frontend/reducers/initialState';
//Get Hashes
import getHashManifest from './getHashManifest';
//App
import App from '../frontend/components/App';
const { env, port } = config;
const routesUrls = routes.map( route => route.path);
const app = express();
if(env === 'development'){
const compiler = webpack(webpackConfig);
const serverConfig = {
serverSideRender: true,
publicPath: webpackConfig.output.publicPath,
};
app
.use(webpackDevMiddleware(compiler, serverConfig))
.use(webpackHotMiddleware(compiler, {
path: '/reload_wss',
heartbeat: 1000,
}));
}else{
const baseUrl = __dirname.replace(/\/server(.*)/,'');
const fullURL = `${baseUrl}` ;
app
.use((req, res, next) => {
if(!req.hashManifest) req.hashManifest = getHashManifest();
next();
})
.use(express.static(fullURL))
.use(helmet())
.use(helmet.permittedCrossDomainPolicies())
.use(helmet({
contentSecurityPolicy: {
directives: {
...helmet.contentSecurityPolicy.getDefaultDirectives(),
'script-src': ['\'self\'', '\'unsafe-inline\''],//"example.com"
},
},
}))
.disable('x-powered-by');
}
const setResponse = (html, preloadedState, manifest) => {
const mainStyles = manifest ? manifest['frontend.css'] : 'assets/app.css';
const mainBuild = manifest ? manifest['frontend.js'] : 'assets/app.js';
const vendorBuild = manifest ? manifest['vendors.js'] : 'assets/vendor.js';
const manifestJson = manifest ? `<link rel="manifest" href="${manifest['manifest.json']}">` : '';
return(`
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<link rel="shortcut icon" href="favicon.ico">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="theme-color" content="#000000">
${manifestJson}
<link href="${mainStyles}" rel="stylesheet" type="text/css"></link>
<title>App</title>
</head>
<body>
<div id="app">${html}</div>
<script>
window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState).replace(/</g, '\\u003c')}
</script>
<script src="${mainBuild}" type="text/javascript"></script>
<script src="${vendorBuild}" type="text/javascript"></script>
</body>
</html>
`);
};
const renderApp = (req, res, next) => {
if(routesUrls.includes(req.url)){
const store = setStore({ initialState });
const preloadedState = store.getState();
const html = renderToString(
<Provider store={store}>
<StaticRouter location={req.url}>
<App />
</StaticRouter>
</Provider>
);
res.send(setResponse(html, preloadedState, req.hashManifest));
}
next();
};
app
.get('*', renderApp);
app.listen(port, (err) => {
if(err) console.error(err);
else console.log(`Server running on port ${port}`);
});

46
tsconfig.json Normal file
View File

@ -0,0 +1,46 @@
{
"extends": "ts-node/node12/tsconfig.json",
"ts-node": {
// It is faster to skip typechecking.
// Remove if you want ts-node to do typechecking.
"transpileOnly": true,
"compilerOptions": {
"module": "commonjs",
}
},
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": false,
"jsx": "react-jsx",
"experimentalDecorators": true,
"types": [
"react/next",
"react-dom/next",
"node"
],
"sourceMap": true,
"baseUrl": "**/*",
},
"include": [
"**/*"
],
"exclude": [
"node_modules"
]
}

109
webpack.config.dev.js Normal file
View File

@ -0,0 +1,109 @@
const path = require('path');
const dotenv = require('dotenv').config();
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const PUBLIC_URL = process.env.PUBLIC_URL || '/';
module.exports = {
entry: ['webpack-hot-middleware/client?path=/reload_wss&timeout=2000&reload=true&autoConnect=true', './src/frontend/index.tsx'],
output: {
path: path.resolve(__dirname, 'build'),
filename: 'assets/app.js',
publicPath: PUBLIC_URL,
},
resolve: {
extensions: ['.js', '.jsx','.ts','.tsx', '.json'],
alias: {
'@components': path.resolve(__dirname, 'src/frontend/components/'),
'@styles': path.resolve(__dirname, 'src/frontend/styles/'),
}
},
devtool: 'inline-source-map',
mode: 'development',
context: __dirname,
module: {
rules: [
{
test: /\.(js|jsx|ts|tsx)$/,
use: {
loader: 'babel-loader',
options: { plugins: ['react-refresh/babel'] }
},
exclude: /node_modules/,
},
{
test: /\.(css|sass|scss)$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader',
],
},
{
test: /\.(png|jpg|jpeg|gif|svg|ico|mp4|avi|ttf|otf|eot|woff|woff2|pdf)$/,
loader: 'file-loader',
options: {
name: 'assets/media/[name].[ext]',
},
},
{
test: /\.(ttf|otf|eot|woff|woff2)$/,
loader: 'url-loader',
options: {
name: 'assets/fonts/[name].[ext]',
esModule: false,
},
},
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new ReactRefreshWebpackPlugin(),
new MiniCssExtractPlugin({
filename: 'assets/app.css',
}),
new ESLintPlugin(),
new webpack.DefinePlugin({
'process.env': JSON.stringify(dotenv.parsed),
'process.env.PUBLIC_URL': JSON.stringify(PUBLIC_URL),
}),
new CopyPlugin({
patterns: [
{
from: './public/manifest.json', to: '',
},
{
from: './public/favicon.ico', to: '',
},
{
from: './public/logo192.png', to: '',
},
{
from: './public/logo512.png', to: '',
},
]
}),
],
optimization: {
splitChunks: {
chunks: 'async',
cacheGroups: {
vendors: {
name: 'vendors',
chunks: 'all',
reuseExistingChunk: true,
priority: 1,
filename: 'assets/vendor.js',
enforce: true,
test (module, chunks){
const name = module.nameForCondition && module.nameForCondition();
return chunks.name !== 'vendors' && /[\\/]node_modules[\\/]/.test(name);
},
},
},
},
},
};

237
webpack.config.js Normal file
View File

@ -0,0 +1,237 @@
const path = require('path');
const dotenv = require('dotenv').config();
const webpack = require('webpack');
const CompressionWebpackPlugin = require('compression-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const { WebpackManifestPlugin } = require('webpack-manifest-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const { InjectManifest } = require('workbox-webpack-plugin');
const nodeExternals = require('webpack-node-externals');
const PUBLIC_URL = process.env.PUBLIC_URL || '/';
const frontendConfig = {
entry: {
frontend: './src/frontend/index.tsx',
},
output: {
path: path.resolve(__dirname, 'build'),
filename: 'assets/app-[name]-[fullhash].js',
publicPath: PUBLIC_URL,
},
resolve: {
extensions: ['.js', '.jsx','.ts','.tsx', '.json'],
alias: {
'@components': path.resolve(__dirname, 'src/frontend/components/'),
'@styles': path.resolve(__dirname, 'src/frontend/styles/'),
}
},
mode: 'production',
module: {
rules: [
{
test: /\.(js|jsx|ts|tsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
{
test: /\.(css|sass|scss)$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader',
],
},
{
test: /\.(png|jpg|jpeg|gif|svg|ico|mp4|avi|ttf|otf|eot|woff|woff2|pdf)$/,
loader: 'file-loader',
options: {
name: 'assets/media/[name].[ext]',
},
},
{
test: /\.(ttf|otf|eot|woff|woff2)$/,
loader: 'url-loader',
options: {
name: 'assets/fonts/[name].[ext]',
esModule: false,
},
},
],
},
plugins: [
new CompressionWebpackPlugin({
test: /\.(js|css)$/,
filename: '[path][base].gz',
}),
new MiniCssExtractPlugin({
filename: 'assets/app-[fullhash].css',
}),
new WebpackManifestPlugin({
fileName: 'assets/manifest-hash.json',
}),
new CleanWebpackPlugin({
cleanOnceBeforeBuildPatterns: [
'**/*',
'!server/**',
],
}),
new ESLintPlugin(),
new webpack.DefinePlugin({
'process.env': JSON.stringify(dotenv.parsed),
'process.env.PUBLIC_URL': JSON.stringify(PUBLIC_URL),
}),
new CopyPlugin({
patterns: [
{
from: './public/manifest.json', to: '',
},
{
from: './public/favicon.ico', to: '',
},
{
from: './public/logo192.png', to: '',
},
{
from: './public/logo512.png', to: '',
},
]
}),
new InjectManifest({
swSrc: './service-worker.js',
swDest: 'service-worker.js',
}),
],
optimization: {
minimize: true,
minimizer: [
new CssMinimizerPlugin(),
new TerserPlugin(),
],
splitChunks: {
chunks: 'async',
cacheGroups: {
vendors: {
name: 'vendors',
chunks: 'all',
reuseExistingChunk: true,
priority: 1,
filename: 'assets/vendor-[name]-[fullhash].js',
enforce: true,
test (module, chunks){
const name = module.nameForCondition && module.nameForCondition();
return chunks.name !== 'vendors' && /[\\/]node_modules[\\/]/.test(name);
},
},
},
},
},
};
const serverConfig = {
entry: {
server: './src/server/index.js',
},
target: "node",
externals: [nodeExternals()],
output: {
path: path.resolve(__dirname, 'build'),
filename: 'server/app-[name].js',
publicPath: PUBLIC_URL,
},
resolve: {
extensions: ['.js', '.jsx','.ts','.tsx', '.json'],
alias: {
'@components': path.resolve(__dirname, 'src/frontend/components/'),
'@styles': path.resolve(__dirname, 'src/frontend/styles/'),
}
},
mode: 'production',
module: {
rules: [
{
test: /\.(js|jsx|ts|tsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
{
test: /\.(css|sass|scss)$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader',
],
},
{
test: /\.(png|jpg|jpeg|gif|svg|ico|mp4|avi|ttf|otf|eot|woff|woff2|pdf)$/,
loader: 'file-loader',
options: {
name: 'assets/media/[name].[ext]',
},
},
{
test: /\.(ttf|otf|eot|woff|woff2)$/,
loader: 'url-loader',
options: {
name: 'assets/fonts/[name].[ext]',
esModule: false,
},
},
],
},
plugins: [
new CompressionWebpackPlugin({
test: /\.(js|css)$/,
filename: '[path][base].gz',
}),
new MiniCssExtractPlugin({
filename: 'assets/app-[fullhash].css',
}),
new WebpackManifestPlugin({
fileName: 'assets/manifest-hash.json',
}),
new CleanWebpackPlugin(),
new ESLintPlugin(),
new webpack.DefinePlugin({
'process.env': JSON.stringify(dotenv.parsed),
'process.env.PUBLIC_URL': JSON.stringify(PUBLIC_URL),
}),
new InjectManifest({
swSrc: './service-worker.js',
swDest: 'service-worker.js',
}),
],
optimization: {
minimize: true,
minimizer: [
new CssMinimizerPlugin(),
new TerserPlugin(),
],
splitChunks: {
chunks: 'async',
cacheGroups: {
vendors: {
name: 'vendors',
chunks: 'all',
reuseExistingChunk: true,
priority: 1,
filename: 'assets/vendor-[name]-[fullhash].js',
enforce: true,
test (module, chunks){
const name = module.nameForCondition && module.nameForCondition();
return chunks.name !== 'vendors' && /[\\/]node_modules[\\/]/.test(name);
},
},
},
},
},
};
module.exports = [frontendConfig, serverConfig];