├── .babelrc ├── .gitignore ├── .npmignore ├── .travis.yaml ├── LICENSE ├── _config.yml ├── cli ├── cli.js ├── cliFileMethods.js └── cliQuestions.js ├── lib ├── index.js ├── performanceTest │ ├── createCompareHTML.js │ ├── createConfig.js │ └── createPrimeServer.js ├── returnHTML.js └── server.js ├── package-lock.json ├── package.json ├── readme.md └── test └── lib.test.js /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["@babel/preset-env", "@babel/preset-react"], 3 | "env": { 4 | "production": { 5 | "plugins": ["transform-react-remove-prop-types"] 6 | } 7 | } 8 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .DS_Store 3 | test/testFiles/* -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | src 3 | .babelrc 4 | .gitignore 5 | test/testFiles/* -------------------------------------------------------------------------------- /.travis.yaml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "10" 4 | - "8" 5 | install: npm install 6 | script: 7 | - npm test -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 SS-React 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 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman -------------------------------------------------------------------------------- /cli/cli.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | /** 4 | * This file is used to execute the CLI for react-prime. It creates a /primessr directory 5 | * in the user's project that contains five files: 6 | * 1. index.js 7 | * 2. server.js 8 | * 3. returnHTML.js 9 | * 4. primeCompare.html, and 10 | * 5. primeServer.js 11 | */ 12 | 13 | const inquirer = require('inquirer'); 14 | const figlet = require('figlet'); 15 | const chalk = require('chalk'); 16 | const fs = require('fs'); 17 | 18 | const cliQuestions = require('./cliQuestions.js'); 19 | const createHTMLScript = require('../lib/returnHTML.js'); 20 | const createIndexScript = require('../lib/index.js'); 21 | const createServerScript = require('../lib/server.js'); 22 | const createCompareScript = require('../lib/performanceTest/createCompareHTML.js'); 23 | const createPrimeServer = require('../lib/performanceTest/createPrimeServer.js'); 24 | const createConfigScript = require('../lib/performanceTest/createConfig.js'); 25 | 26 | // chalk adds color and weight ton cli fonts 27 | console.log((chalk.rgb(46, 255, 0).bgBlack.bold(figlet.textSync('React Prime', { 28 | // chalk is setting the color etc. of large text and background, figlet is making the large text 29 | font: 'Big', 30 | horizontalLayout: 'default', 31 | verticalLayout: 'default', 32 | })))); 33 | 34 | inquirer.prompt(cliQuestions).then((answers) => { 35 | // check is ssr folder exists if not create one 36 | if (!fs.existsSync('./primessr')) { 37 | fs.mkdirSync('./primessr'); 38 | fs.mkdirSync('./primessr/performanceTest'); 39 | fs.mkdirSync('./primessr/performanceTest/reports'); 40 | } 41 | 42 | fs.readFile('package.json', 'utf8', (error, result) => { 43 | if (error) throw error; 44 | 45 | const tempObj = Object.assign({}, JSON.parse(result)); 46 | tempObj.scripts['prime:compare'] = `npm run ${answers.startScript} & npm run prime:server & node ./primessr/performanceTest/primeServer.js`; 47 | tempObj.scripts['prime:server'] = 'NODE_ENV=production node ./primessr/index.js'; 48 | tempObj.scripts['prime:CSRreport'] = `lighthouse --config-path=./primessr/performanceTest/custom-config.js --output html --output-path ./primessr/performanceTest/reports/csr-report.html http://localhost:${answers.port}`; 49 | tempObj.scripts['prime:SSRreport'] = 'lighthouse --config-path=./primessr/performanceTest/custom-config.js --output html --output-path ./primessr/performanceTest/reports/ssr-report.html http://localhost:8080'; 50 | fs.writeFileSync('package.json', JSON.stringify(tempObj, null, 2)); 51 | }); 52 | 53 | fs.writeFileSync('./primessr/performanceTest/primeCompare.html', createCompareScript(answers)); 54 | fs.writeFileSync('./primessr/performanceTest/primeServer.js', createPrimeServer()); 55 | fs.writeFileSync('./primessr/performanceTest/custom-config.js', createConfigScript()); 56 | fs.writeFileSync('./primessr/index.js', createIndexScript()); 57 | fs.writeFileSync('./primessr/server.js', createServerScript(answers)); 58 | fs.writeFileSync('./primessr/returnHTML.js', createHTMLScript(answers)); 59 | 60 | console.log(chalk.blue('\n---------------Completed---------------\n')); 61 | console.log(chalk.blue('Run "npm run prime:compare" to see a comparison of your website')); 62 | console.log(chalk.blue('Or, run "npm run prime:server" to see an SSR version of your app\n\n')); 63 | }); 64 | -------------------------------------------------------------------------------- /cli/cliFileMethods.js: -------------------------------------------------------------------------------- 1 | const fuzzy = require('fuzzy'); 2 | const glob = require('glob'); 3 | 4 | const cliFileMethods = {}; 5 | 6 | const folderDir = glob.sync('**/*/', { ignore: '**/node_modules/**' }).map((ele) => { 7 | const newDir = `${ele.slice(0, -1)}`; 8 | return newDir; 9 | }); 10 | const fileList = glob.sync('**/*.{js,jsx}', { ignore: '**/node_modules/**', nodir: true }); 11 | const htmlList = glob.sync('**/*.html', { ignore: '**/node_modules/**' }); 12 | 13 | cliFileMethods.searchFolders = (answers, input) => { 14 | const userInput = input || ''; 15 | 16 | return new Promise(((resolve) => { 17 | const fuzzyResult = fuzzy.filter(userInput, folderDir); 18 | resolve( 19 | fuzzyResult.map(ele => ele.original), 20 | ); 21 | })); 22 | }; 23 | 24 | cliFileMethods.searchFiles = (answers, input) => { 25 | const userInput = input || ''; 26 | 27 | return new Promise(((resolve) => { 28 | const fuzzyResult = fuzzy.filter(userInput, fileList); 29 | resolve( 30 | fuzzyResult.map(ele => ele.original), 31 | ); 32 | })); 33 | }; 34 | 35 | cliFileMethods.searchHtml = (answers, input) => { 36 | const userInput = input || ''; 37 | 38 | return new Promise(((resolve) => { 39 | const fuzzyResult = fuzzy.filter(userInput, htmlList); 40 | resolve( 41 | fuzzyResult.map(ele => ele.original), 42 | ); 43 | })); 44 | }; 45 | 46 | module.exports = { 47 | cliFileMethods, 48 | folderDir, 49 | fileList, 50 | htmlList, 51 | }; 52 | -------------------------------------------------------------------------------- /cli/cliQuestions.js: -------------------------------------------------------------------------------- 1 | const inquirer = require('inquirer'); 2 | const chalk = require('chalk'); 3 | const chalkAnimation = require('chalk-animation') 4 | 5 | const { 6 | cliFileMethods, folderDir, fileList, htmlList, 7 | } = require('./cliFileMethods'); 8 | 9 | inquirer.registerPrompt('autocomplete', require('inquirer-autocomplete-prompt')); 10 | 11 | const cliQuestions = [ 12 | { 13 | type: 'autocomplete', 14 | name: 'static', 15 | suggestOnly: true, 16 | message: chalk.rgb(46, 255, 0)('Type the directory containing your bundle:'), 17 | source: cliFileMethods.searchFolders, 18 | validate(answer) { 19 | if (!folderDir.includes(answer)) { 20 | return chalk.rgb(255, 0, 0).bold('Invalid entry point'); 21 | } 22 | return true; 23 | }, 24 | }, 25 | { 26 | type: 'input', 27 | name: 'startScript', 28 | message: chalk.rgb(46, 255, 0)('Type in the name of the npm script that starts your server:'), 29 | validate(answer) { 30 | if (answer.length === 0) { 31 | return chalk.rgb(255, 0, 0).bold('Enter a valid name'); 32 | } 33 | return true; 34 | }, 35 | }, 36 | { 37 | type: 'input', 38 | name: 'port', 39 | message: chalk.rgb(46, 255, 0)('Type in the port number of your client side server:'), 40 | validate(answer) { 41 | if (answer.length === 0 || typeof JSON.parse(answer) !== 'number') { 42 | return chalk.rgb(255, 0, 0).bold('Enter a valid number'); 43 | } 44 | return true; 45 | }, 46 | }, 47 | { 48 | type: 'autocomplete', 49 | name: 'component', 50 | suggestOnly: true, 51 | message: chalk.rgb(46, 255, 0)('Type the path of your root component:'), 52 | source: cliFileMethods.searchFiles, 53 | validate(answer) { 54 | if (!fileList.includes(answer)) { 55 | return chalk.rgb(255, 0, 0).bold('Invalid entry point'); 56 | } 57 | return true; 58 | }, 59 | }, 60 | { 61 | type: 'autocomplete', 62 | name: 'rootHtml', 63 | suggestOnly: true, 64 | message: chalk.rgb(46, 255, 0)('Type the path of the /build HTML file containing the root div:'), 65 | source: cliFileMethods.searchHtml, 66 | validate(answer) { 67 | if (!htmlList.includes(answer)) { 68 | return chalk.rgb(255, 0, 0).bold('Invalid entry point'); 69 | } 70 | return true; 71 | }, 72 | }, 73 | ]; 74 | 75 | module.exports = cliQuestions; 76 | -------------------------------------------------------------------------------- /lib/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Function that returns a string to make an index file for the SSR version of the user's app 3 | */ 4 | 5 | const index = () => { 6 | return `const md5File = require('md5-file'); 7 | const path = require('path'); 8 | 9 | // Ignore CSS styles imported on load 10 | const ignoreStyles = require('ignore-styles'); 11 | const register = ignoreStyles.default; 12 | 13 | // When running locally these will load from a standard import 14 | // When running on the server, we want to load via their hashed version in the build folder 15 | const extensions = ['.gif', '.jpeg', '.jpg', '.png', '.svg']; 16 | 17 | // Override the default style ignorer, also modifying all image requests 18 | register(ignoreStyles.DEFAULT_EXTENSIONS, (mod, filename) => { 19 | if (!extensions.find(f => filename.endsWith(f))) { 20 | // If we find a style 21 | return ignoreStyles.noOp(); 22 | } 23 | const hash = md5File.sync(filename).slice(0, 8); 24 | const bn = path.basename(filename).replace(/(\\.\\w{3})$/, \`.\${hash}$1\`); 25 | 26 | mod.exports = \`/static/media/\${bn}\`; 27 | }); 28 | 29 | // require babel to transpile JSX 30 | // allow imports and code splitting through plugins 31 | require('@babel/register')({ 32 | presets: ['@babel/preset-env', '@babel/preset-react'], 33 | plugins: [ 34 | '@babel/plugin-syntax-dynamic-import', 35 | 'dynamic-import-node', 36 | 'react-loadable/babel' 37 | ] 38 | }); 39 | 40 | // import the server 41 | require('./server');`; 42 | }; 43 | 44 | module.exports = index; 45 | -------------------------------------------------------------------------------- /lib/performanceTest/createCompareHTML.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Function that returns a string to create an HTML comparison file 3 | * @param {Object} input - Object containing user input from CLI (requires the .port property) 4 | */ 5 | 6 | const createCompareHTML = (input) => { 7 | return ` 8 | 9 | 10 | 11 | React Prime 12 | 106 | 107 | 108 | 109 |
110 |
111 |
112 |

Client-Side Rendered

113 |
114 | 115 |
116 |
VIEW 117 | REPORT 118 |
119 | 120 |
121 |
122 |
123 |
124 |

Server-Side Rendered

125 |
126 | 127 |
128 |
VIEW 129 | REPORT 130 |
131 | 132 |
133 |
134 |
135 | 136 | `; 137 | }; 138 | 139 | module.exports = createCompareHTML; 140 | -------------------------------------------------------------------------------- /lib/performanceTest/createConfig.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Function that returns a string to create a Google Lighthouse config file 3 | */ 4 | 5 | const createConfig = () => { 6 | return `module.exports = { 7 | extends: 'lighthouse:default', 8 | settings: { 9 | throttlingMethod: 'devtools', 10 | onlyCategories: ['performance'], 11 | }, 12 | };`; 13 | }; 14 | 15 | module.exports = createConfig; 16 | -------------------------------------------------------------------------------- /lib/performanceTest/createPrimeServer.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Function that returns a string to create a server file for the prime:compare npm script 3 | */ 4 | 5 | const createPrimeServer = () => { 6 | return `const express = require('express'); 7 | const path = require('path'); 8 | 9 | const app = express(); 10 | 11 | const port = 5050; 12 | 13 | app.use('/csr-report', express.static(path.join(__dirname, './reports/csr-report.html'))); 14 | app.use('/ssr-report', express.static(path.join(__dirname, './reports/ssr-report.html'))); 15 | 16 | app.get('/', (req, res) => { 17 | res.sendFile(path.join(__dirname, './primeCompare.html')); 18 | }); 19 | app.listen(port, () => console.log('Listening on port 5050, ready to compare')); 20 | `; 21 | }; 22 | 23 | module.exports = createPrimeServer; 24 | -------------------------------------------------------------------------------- /lib/returnHTML.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @param {Object} input - Object containing user input from CLI 4 | * (requires the .component and .rootHTML properties) 5 | */ 6 | 7 | const returnHTML = (input) => { 8 | return `// standard react modules 9 | import React from 'react'; 10 | import { renderToString } from 'react-dom/server'; 11 | // security middleware 12 | import Helmet from 'react-helmet'; 13 | // required for react router 14 | import { StaticRouter } from 'react-router'; 15 | // frontload helps when trying to render react components that need to 16 | // retrieve data asynchronously 17 | import { Frontload, frontloadServerRender } from 'react-frontload'; 18 | import Loadable from 'react-loadable'; 19 | import path from 'path'; 20 | import fs from 'fs'; 21 | 22 | // main entrypoint and manifest (included in CRA) 23 | import App from '../${input.component}'; 24 | import manifest from '../build/asset-manifest.json'; 25 | 26 | // export middleware that returns stringified HTML from server 27 | const returnHTML = (req, res) => { 28 | const injectHTML = (data, { html, title, meta, body, scripts }) => { 29 | data = data.replace('', \`\`); 30 | data = data.replace(/.*?<\\/title>/g, title); 31 | data = data.replace('</head>', \`\${meta}</head>\`); 32 | data = data.replace( 33 | '<div id="root"></div>', 34 | \`<div id="root">\${body}</div>\` 35 | ); 36 | data = data.replace('</body>', scripts.join('') + '</body>'); 37 | 38 | return data; 39 | }; 40 | 41 | fs.readFile( 42 | path.resolve(__dirname, '../${input.rootHtml}'), 43 | 'utf8', 44 | (err, htmlData) => { 45 | if (err) { 46 | console.error('Read error', err); 47 | return res.status(404).end(); 48 | } 49 | 50 | // define context for react router 51 | const context = {}; 52 | // define modules for react loadable 53 | const modules = []; 54 | 55 | frontloadServerRender(() => 56 | renderToString( 57 | <Loadable.Capture report={m => modules.push(m)}> 58 | <StaticRouter location={req.url} context={context}> 59 | <Frontload isServer> 60 | <App /> 61 | </Frontload> 62 | </StaticRouter> 63 | </Loadable.Capture> 64 | ) 65 | ).then(routeMarkup => { 66 | if (context.url) { 67 | // If context has a url property, then we need to handle a redirection in Redux Router 68 | res.writeHead(302, { 69 | Location: context.url 70 | }); 71 | 72 | res.end(); 73 | } else { 74 | // Otherwise, we carry on... 75 | 76 | // Let's give ourself a function to load all our page-specific JS assets for code splitting 77 | const extractAssets = (assets, chunks) => 78 | Object.keys(assets) 79 | .filter(asset => chunks.indexOf(asset.replace('.js', '')) > -1) 80 | .map(k => assets[k]); 81 | 82 | // Let's format those assets into pretty <script> tags 83 | const extraChunks = extractAssets(manifest, modules).map( 84 | c => \`<script type="text/javascript" src="/\${c}"></script>\` 85 | ); 86 | 87 | // We need to tell Helmet to compute the right meta tags, title, and such 88 | const helmet = Helmet.renderStatic(); 89 | 90 | // Pass all this nonsense into our HTML formatting function above 91 | const html = injectHTML(htmlData, { 92 | html: helmet.htmlAttributes.toString(), 93 | title: helmet.title.toString(), 94 | meta: helmet.meta.toString(), 95 | body: routeMarkup, 96 | scripts: extraChunks 97 | }); 98 | 99 | // We have all the final HTML, let's send it to the user already! 100 | res.status(200).send(html); 101 | } 102 | }); 103 | } 104 | ); 105 | } 106 | export default returnHTML`; 107 | }; 108 | 109 | module.exports = returnHTML; 110 | -------------------------------------------------------------------------------- /lib/server.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @param {Object} input - Object containing user input from CLI (requires the .static property) 4 | */ 5 | 6 | const server = (input) => { 7 | return `const express = require('express'); 8 | const bodyParser = require('body-parser'); 9 | const path = require('path'); 10 | const compression = require('compression'); 11 | const Loadable = require('react-loadable'); 12 | 13 | // import middleware to return HTML on server request 14 | import returnHTML from './returnHTML'; 15 | 16 | const app = express(); 17 | const PORT = 8080; 18 | 19 | // apply middleware 20 | app.use(compression()); 21 | app.use(bodyParser.json()); 22 | app.use(bodyParser.urlencoded({ extended: false })); 23 | 24 | /* 25 | NOTE: captures all routes and returns the user's HTML 26 | (may not be ideal for non-SPAs) 27 | */ 28 | app.use(express.Router().get('/', returnHTML)); 29 | app.use(express.static(path.resolve(__dirname, \`../${input.static}\`))); 30 | app.use(returnHTML); 31 | 32 | Loadable.preloadAll().then(() => { 33 | app.listen(PORT, () => { 34 | console.log(\`Listening on \${PORT}...\`); 35 | }); 36 | }); 37 | 38 | app.on('error', (err) => { 39 | if (err) { 40 | console.log(\`Error: \${error}\`); 41 | throw err; 42 | } 43 | });`; 44 | }; 45 | 46 | module.exports = server; 47 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-prime", 3 | "version": "0.1.2", 4 | "description": "Transform your native, non-SSR React applications into responsive, and user friendly applications through SSR.", 5 | "main": "./cli/cli.js", 6 | "directories": { 7 | "assets": "assets", 8 | "build": "build", 9 | "cli": "cli", 10 | "lib": "lib", 11 | "src": "src", 12 | "test": "test" 13 | }, 14 | "scripts": { 15 | "test": "jest --detectOpenHandles" 16 | }, 17 | "repository": { 18 | "type": "git", 19 | "url": "git+https://github.com/SS-React/react-prime" 20 | }, 21 | "bin": { 22 | "prime": "./cli/cli.js" 23 | }, 24 | "keywords": [ 25 | "react", 26 | "ssr", 27 | "server side rendering", 28 | "react router", 29 | "isomorphic", 30 | "universal", 31 | "service workers", 32 | "caching" 33 | ], 34 | "author": "SS-React", 35 | "license": "MIT", 36 | "bugs": { 37 | "url": "https://github.com/SS-React/react-prime/issues" 38 | }, 39 | "homepage": "https://github.com/SS-React/react-prime#readme", 40 | "resolutions": { 41 | "babel-core": "7.0.0-bridge.0" 42 | }, 43 | "dependencies": { 44 | "@babel/register": "^7.0.0", 45 | "babel-core": "^7.0.0-bridge.0", 46 | "chalk": "^2.4.1", 47 | "chalk-animation": "^1.6.0", 48 | "cli-progress": "^2.1.0", 49 | "colors": "^1.3.2", 50 | "express": "^4.16.4", 51 | "figlet": "^1.2.1", 52 | "fs": "0.0.1-security", 53 | "fuzzy": "^0.1.3", 54 | "glob": "^7.1.3", 55 | "ignore-styles": "^5.0.1", 56 | "inquirer": "^6.2.0", 57 | "inquirer-autocomplete-prompt": "^1.0.1", 58 | "inquirer-checkbox-plus-prompt": "^1.0.1", 59 | "lighthouse": "^3.2.1", 60 | "md5-file": "^4.0.0", 61 | "path": "^0.12.7", 62 | "react": "^16.5.2", 63 | "react-dom": "^16.5.2", 64 | "react-frontload": "^1.0.3", 65 | "react-helmet": "^5.2.0", 66 | "react-router": "^4.3.1", 67 | "react-router-dom": "^4.3.1", 68 | "uglify-js": "^3.4.9" 69 | }, 70 | "devDependencies": { 71 | "@babel/core": "^7.1.2", 72 | "@babel/preset-env": "^7.1.0", 73 | "@babel/preset-react": "^7.0.0", 74 | "babel-cli": "^6.26.0", 75 | "babel-loader": "^8.0.2", 76 | "jest": "^23.6.0", 77 | "shebang-loader": "0.0.1" 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | <img src="http://zillberrycom.fatcow.com/react-prime/prime_dark_sm.png" width="250"> 2 | 3 | [![MIT license](http://img.shields.io/badge/license-MIT-brightgreen.svg)](http://opensource.org/licenses/MIT) [![npm version](https://badge.fury.io/js/react-prime.svg)](https://badge.fury.io/js/react-prime) ![alt text](https://david-dm.org/andyahn91/react-prime.svg) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/91b75ab8918b4ef19e43b266e5ee17f1)](https://app.codacy.com/app/andyahn91/react-prime?utm_source=github.com&utm_medium=referral&utm_content=andyahn91/react-prime&utm_campaign=Badge_Grade_Dashboard) 4 | 5 | Library to effortlessly convert your non-SSR React applications into responsive, SSR React applications. 6 | https://ss-react.github.io/react-prime/ 7 | 8 | ## Please Note 9 | 10 | This library has been developed to work with Create-React-Apps exclusively. <br /> 11 | Dependencies that rely on the window object before checking if it exists will not be compatable with React-Prime. 12 | 13 | ## Getting Started 14 | 15 | These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. See deployment for notes on how to deploy the project on a live system. 16 | 17 | ### Installing 18 | 19 | Local installation 20 | 21 | ``` 22 | npm install --save react-prime 23 | ``` 24 | Then, install the required dependencies 25 | ``` 26 | npm i inquirer @babel/core @babel/plugin-syntax-dynamic-import @babel/preset-env @babel/preset-react @babel/register react-frontload react-helmet react-loadable md5-file 27 | ``` 28 | 29 | 30 | ### Server-Side Rendering 31 | 32 | The process of SSR with our library has been automated through a CLI. 33 | 34 | - Add a script into your package.json and run the script. 35 | 36 | ``` 37 | scripts: { 38 | "prime": "prime" 39 | } 40 | ``` 41 | ``` 42 | npm run prime 43 | ``` 44 | <hr> 45 | <img src="http://zillberrycom.fatcow.com/react-prime/react-prime-cli.png" width="650"> 46 | <hr> 47 | 48 | ## Deployment 49 | 50 | Upon answering all of the CLI questions, a ```primessr``` directory is created which contains five files: 51 | - index.js 52 | - server.js 53 | - primeServer.js 54 | - primeCompare.html 55 | 56 | and either 57 | - returnHTML.js 58 | 59 | or, if you have Redux 60 | - returnReduxHTML.js 61 | 62 | Then, an SSR version of your application is automatically hosted on ```http://localhost:8080```. 63 | 64 | ## Performance Testing 65 | 66 | To view side by side comparison of CSR and SSR renders: 67 | ``` 68 | prime:compare 69 | ``` 70 | 71 | While Prime compare server is running, execute the following to generate Lighthouse reports: 72 | ``` 73 | prime:CSRreport 74 | ``` 75 | ``` 76 | prime:SSRreport 77 | ``` 78 | 79 | ## Authors 80 | 81 | * [Andrew Wong](https://github.com/andwong91) 82 | * [Andy Ahn](https://github.com/andyahn91) 83 | * [Brittany Miltenberger](https://github.com/brittanywm) 84 | * [Greg Domingue](https://​github.com/gregdoming) 85 | 86 | See also the list of [contributors](https://github.com/SS-React/react-prime/graphs/contributors) who participated in this project. 87 | 88 | ## License 89 | 90 | This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details 91 | 92 | ## Acknowledgments 93 | 94 | * Thank you to [Patrick Cason](https://medium.com/@cereallarceny/server-side-rendering-in-create-react-app-with-all-the-goodies-without-ejecting-4c889d7db25e) for his excellent article on SSR. 95 | * Huge shoutout to [Clariz Mariano](https://github.com/havengoer) for the logo. You can find more of her work on [dribbble](https://dribbble.com/clarizmariano)! 96 | -------------------------------------------------------------------------------- /test/lib.test.js: -------------------------------------------------------------------------------- 1 | import createIndexScript from '../lib/index'; 2 | import createServerScript from '../lib/server'; 3 | import createHTMLScript from '../lib/returnHTML'; 4 | import createCompareScript from '../lib/performanceTest/createCompareHTML'; 5 | import createPrimeServer from '../lib/performanceTest/createPrimeServer'; 6 | 7 | const fs = require('fs'); 8 | const path = require('path'); 9 | 10 | describe('Testing ./lib files', () => { 11 | const inputObj = { 12 | static: 'build', 13 | component: 'App.js', 14 | rootHtml: 'index.html', 15 | port: 3000 16 | }; 17 | 18 | const mkdir = () => { 19 | if (!fs.existsSync('./test/testFiles')) { 20 | fs.mkdirSync('./test/testFiles'); 21 | } 22 | } 23 | fs.writeFileSync(path.join(__dirname, './testFiles/primeCompare.html')) 24 | 25 | const deleteFile = () => { 26 | fs.unlinkSync(path.join(__dirname, './testFiles/index.js')); 27 | fs.unlinkSync(path.join(__dirname, './testFiles/server.js')); 28 | fs.unlinkSync(path.join(__dirname, './testFiles/primeCompare.html')); 29 | fs.unlinkSync(path.join(__dirname, './testFiles/returnHTML.js')); 30 | fs.unlinkSync(path.join(__dirname, './testFiles/primeServer.js')); 31 | }; 32 | 33 | beforeAll(() => { 34 | mkdir(); 35 | deleteFile(); 36 | }); 37 | 38 | describe(`index.js`, () => { 39 | test(`should return a string`, () => { 40 | expect(typeof createIndexScript()).toBe('string'); 41 | }); 42 | test(`output string should match contents of file created from the string`, () => { 43 | fs.writeFileSync(path.join(__dirname, './testFiles/index.js'), createIndexScript()); 44 | fs.readFileSync(path.join(__dirname, './testFiles/index.js'), (err, data) => { 45 | expect(createIndexScript()).toBe(data); 46 | }); 47 | }); 48 | }); 49 | describe(`server.js`, () => { 50 | test(`should return a string`, () => { 51 | expect(typeof createServerScript(inputObj)).toBe('string'); 52 | }); 53 | test(`output string should match contents of file created from the string`, () => { 54 | fs.writeFileSync(path.join(__dirname, './testFiles/server.js'), createServerScript(inputObj)); 55 | fs.readFileSync(path.join(__dirname, './testFiles/server.js'), (err, data) => { 56 | expect(createServerScript(inputObj)).toBe(data); 57 | }); 58 | }); 59 | }); 60 | describe(`primeCompare.html`, () => { 61 | test(`should return a string`, () => { 62 | expect(typeof createCompareScript(inputObj)).toBe('string'); 63 | }); 64 | test(`output string should match contents of file created from the string`, () => { 65 | fs.writeFileSync(path.join(__dirname, './testFiles/primeCompare.html'), createCompareScript(inputObj)); 66 | fs.readFileSync(path.join(__dirname, './testFiles/primeCompare.html'), (err, data) => { 67 | expect(createCompareScript(inputObj)).toBe(data); 68 | }); 69 | }); 70 | }); 71 | describe(`returnHTML.js`, () => { 72 | test(`should return a string`, () => { 73 | expect(typeof createHTMLScript(inputObj)).toBe('string'); 74 | }); 75 | test(`output string should match contents of file created from the string`, () => { 76 | fs.writeFileSync(path.join(__dirname, './testFiles/returnHTML.js'), createHTMLScript(inputObj)); 77 | fs.readFileSync(path.join(__dirname, './testFiles/returnHTML.js'), (err, data) => { 78 | expect(createHTMLScript(inputObj)).toBe(data); 79 | }); 80 | }); 81 | }); 82 | describe(`createPrimeServer.js`, () => { 83 | test(`should return a string`, () => { 84 | expect(typeof createPrimeServer()).toBe('string'); 85 | }); 86 | test(`output string should match contents of file created from the string`, () => { 87 | fs.writeFileSync(path.join(__dirname, './testFiles/primeServer.js'), createPrimeServer()); 88 | fs.readFileSync(path.join(__dirname, './testFiles/primeServer.js'), (err, data) => { 89 | expect(createPrimeServer()).toBe(data); 90 | }); 91 | }); 92 | }); 93 | }); 94 | --------------------------------------------------------------------------------