Creating a Universal Application with React.js generally involves creating server-side rendered applications. Here are the basics:
1. First, you should install Node.js in your development environment.
1. Install ExpressJs which is a minimal web application framework for Node.js. To install it, open your terminal and type the command.
npm install express —save1. After installing it, install React and ReactDOM for the application. You can install them the same way you installed ExpressJs.
npm install react react-dom —save1. Now you will have to install Babel, which is a JavaScript compiler that converts edge JavaScript into plain old ES5 JavaScript that can run in any browser.
The form of command is: npm installbabel/core
babel/preset-react @babel/preset-env babel-loader —save-dev
You’ll need this because ECMAScript 6 is standardized but it is not fully supported yet.
1. Create a `.babelrc` file in the root of your project that looks like this: \`\`\`javascript { “presets”: [“@babel/preset-env”, “@babel/preset-react”], } \`\`\`
1. Now you have to configure webpack. Webpack is a static module bundler for modern JavaScript applications.
Install Webpack and related modules using npm: npm install webpack webpack-cli webpack-node-externals —save-dev1. Create a “webpack.config.js” file in the root of your project and add this code snippet:
\`\`\`js const path = require(‘path’) const nodeExternals = require(‘webpack-node-externals’) module.exports = { entry: ‘./src/server.js’, target: ‘node’, externals: [nodeExternals()], output: { path: path.resolve(‘server-build’), filename: ‘index.js‘ }, module: { rules: [ { test: /.jsx?$/, exclude: /node\_modules/, use: { loader: ‘babel-loader‘ } }, ] } } \`\`\`1. Now, you need to create a Server. To do this, first, create a new directory named ‘src’ and make a new file ‘server.js’ inside it.
1. Add this code to your server.js that will render a simple component.
\`\`\`js import express from ‘express’; import React from ‘react’; import ReactDOMServer from ‘react-dom/server’; const app = express(); const PORT = 3000; app.use(‘^/$’, (req, res) => { const application = ReactDOMServer.renderToString(1. Create a new file called app.js in the same directory. Add the following code to it:
\`\`\`js import React from ‘react’; const App = () => { return1. Now add the following start script to your package.json file to start your server:
\`\`\`javascript { “scripts”: { “start”: “babel-node src/server.js“ } } \`\`\` 1. Now, you can run the application by typing `npm start` in your terminal.Remember to always restart your server whenever you make changes in your server.js.
This is the basic structure of a universal web application with server-side rendering. It becomes more complex as you add routes, CSS, APIs etc. There are also a number of boilerplates and starter-kits available on GitHub to kickstart the process.