<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Anshuman Chhapolia on Medium]]></title>
        <description><![CDATA[Stories by Anshuman Chhapolia on Medium]]></description>
        <link>https://medium.com/@achhapolia10?source=rss-f8fcbcada017------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JFjX3NeO-rxIjcUtfKU7oQ.jpeg</url>
            <title>Stories by Anshuman Chhapolia on Medium</title>
            <link>https://medium.com/@achhapolia10?source=rss-f8fcbcada017------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 22:03:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@achhapolia10/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Server-Side Rendering using React and Express — Part 2]]></title>
            <link>https://medium.com/swlh/server-side-rendering-using-react-and-express-part-2-a88360f5667f?source=rss-f8fcbcada017------2</link>
            <guid isPermaLink="false">https://medium.com/p/a88360f5667f</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[express]]></category>
            <category><![CDATA[babel]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[webpack]]></category>
            <dc:creator><![CDATA[Anshuman Chhapolia]]></dc:creator>
            <pubDate>Mon, 25 May 2020 11:08:11 GMT</pubDate>
            <atom:updated>2020-05-26T03:19:08.479Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*sGGiwo4fFXVGBAdVTan8bg.png" /></figure><h3>Server-Side Rendering using React and Express — Part 2</h3><h4>Understanding the tools used and their config files</h4><p>When I started learning React, most of the courses and the online guides suggested using <strong><em>create-react-app. </em></strong>CRA is a great tool to quickly bootstrap a project, but it doesn’t expose the config files out of the box. At the moment, it felt like a perfect tool for creating React projects, but when I started doing complex projects, I faced some difficulties. I needed to change the config files so I ran the eject script. First look at those config files was daunting. Somehow I managed to make the necessary changes. In the next project, I needed to do Search Engine Optimization (SEO). Next.js seemed to be a perfect tool for it. As I used it more I started getting the feeling that I am losing control over my code. So I started working on setting up a project myself for Server-Side Rendering. A huge amount of time was spent researching the tools and writing the config files for them. So I’ll start by explaining the tools and cover how to write the config files for them.</p><h3>Babel</h3><blockquote>Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments.</blockquote><p>Node.js and browsers don’t support JSX. We need tools to transpile it into JavaScript syntax before it can be run by Node.js or the browser. We use babel for this. It’s simple to configure, has a <a href="https://babeljs.io/docs/en/babel-cli">CLI</a> and a require hook (<a href="https://babeljs.io/docs/en/babel-register">@babel/register</a>). This makes it a suitable tool for our project.</p><p>A Babel config is named .babelrc.json. We can also write the config in JavaScript to generate configuration dynamically.</p><p><strong>.babelrc.json</strong></p><pre>&quot;presets&quot;: [<br>    [<br>      &quot;@babel/preset-env&quot;,<br>      {<br>        &quot;targets&quot;: {<br>          &quot;node&quot;: &quot;current&quot;<br>        }<br>      }<br>    ],<br>    [<br>      &quot;@babel/preset-react&quot;<br>    ]<br>  ],<br>  &quot;plugins&quot;: [<br>    &quot;@babel/plugin-proposal-class-properties&quot;<br>  ],<br>  &quot;ignore&quot;: [<br>    &quot;src/static/**/*&quot;<br>  ]<br>}</pre><p>To perform transpiling using Babel we need to add some plugins in its configuration file. Here I’ve used one plugin explicitly.</p><ul><li><a href="https://babeljs.io/docs/en/babel-plugin-proposal-class-properties">@babel/plugin-proposal-class-properties</a>: This plugin enables us to use static properties in classes in JavaScript.</li></ul><p>Presets are a set of plugins assembled so that we don’t have to do that task ourselves.</p><ul><li><a href="https://babeljs.io/docs/en/babel-preset-env">@babel/preset-env</a>: This preset lets us use the latest feature of Javascript in our code which isn’t supported by Node.js yet.</li><li><a href="https://babeljs.io/docs/en/babel-preset-react">@babel/preset-react</a>: This preset lets us use the JSX and other features of React in our code.</li></ul><h3>Webpack</h3><blockquote>At its core, <strong>webpack </strong>is a <em>static module bundler</em> for modern JavaScript applications.</blockquote><p>Webpack is used here to bundle the react code for the browser. It takes an <strong>entry</strong> which is the point where our code starts executing. Webpack creates a <strong>Dependency Graph</strong> which maps every module our project needs and creates one or more bundles based on its configuration. <strong>Loaders</strong> are transformations applied to the code of the module before it is bundled by webpack. <strong>Plugins</strong> are used in webpack to perform operations other than bundling which is very useful.</p><p><strong>webpack.config.js</strong></p><pre>const path = require(&#39;path&#39;)<br>const HtmlWebpackPlugin = require(&#39;html-webpack-plugin&#39;)<br>const { CleanWebpackPlugin } = require(&#39;clean-webpack-plugin&#39;)<br>const MiniCssExtractPlugin = require(&#39;mini-css-extract-plugin&#39;)<br>const production = process.env.NODE_ENV === &#39;production&#39;</pre><pre>const pages = [&#39;index&#39;, &#39;about&#39;]</pre><pre>const generateEntryPoints = (entry) =&gt; {<br>  return entry.reduce((obj, item) =&gt; {<br>    return {<br>      ...obj,<br>      [item]: [path.resolve(&#39;src&#39;, &#39;components&#39;, &#39;entrypoints&#39;, `${item}.jsx`)]<br>    }<br>  }, {})<br>}</pre><pre>const generateHtml = (entry) =&gt; {<br>  return entry.map((i) =&gt; {<br>    return new HtmlWebpackPlugin({<br>      chunks: [i],<br>      filename: `../views/pages/${i}.ejs`,<br>      template: path.join(&#39;src&#39;, &#39;views&#39;, &#39;pages&#39;, &#39;template.ejs&#39;)<br>    })<br>  })<br>}</pre><pre>const config = [{<br>  entry: {<br>    ...generateEntryPoints(pages)<br>  },</pre><pre>output: {<br>    path: production ? path.resolve(__dirname, &#39;dist&#39;, &#39;static&#39;, &#39;public&#39;) : path.resolve(__dirname, &#39;src&#39;, &#39;static&#39;, &#39;public&#39;),<br>    filename: production ? &#39;js/[chunkhash].js&#39; : &#39;js/[name].js&#39;,<br>    publicPath: &#39;/public&#39;<br>  },</pre><pre>module: {<br>    rules: [<br>      {<br>        test: /\.(js|jsx)$/,<br>        use: {<br>          loader: &#39;babel-loader&#39;,<br>          options: {<br>            presets: [&#39;@babel/preset-env&#39;, &#39;@babel/preset-react&#39;]<br>          }<br>        },<br>        exclude: [/node_modules/, /static/]<br>      }, {<br>        test: /\.ejs$/,<br>        loader: &#39;raw-loader&#39;<br>      }, {<br>        test: /\.(css)$/,<br>        use: [{<br>          loader: MiniCssExtractPlugin.loader,<br>          options: {<br>            publicPath: &#39;/public/css&#39;<br>          }</pre><pre>}, &#39;css-loader&#39;]<br>      }, {<br>        test: /\.(jpg|jpeg|png|svg|gif)$/,<br>        use: [{<br>          loader: &#39;file-loader&#39;,<br>          options: {<br>            name: &#39;[md5:hash:hex].[ext]&#39;,<br>            publicPath: &#39;/public/img&#39;,<br>            outputPath: &#39;img&#39;<br>          }<br>        }]<br>      }<br>    ]<br>  },</pre><pre>resolve: {<br>    extensions: [&#39;.js&#39;, &#39;.jsx&#39;, &#39;.json&#39;, &#39;.wasm&#39;, &#39;.mjs&#39;, &#39;*&#39;]<br>  },</pre><pre>optimization: {<br>    splitChunks: {<br>      automaticNameDelimiter: &#39;.&#39;,<br>      cacheGroups: {<br>        react: {<br>          chunks: &#39;initial&#39;<br>        }<br>      }<br>    }<br>  },</pre><pre>plugins: [<br>    new CleanWebpackPlugin(),<br>    new MiniCssExtractPlugin({<br>      filename: production ? &#39;css/[contentHash].css&#39; : &#39;css/[id].css&#39;,<br>      chunkFilename: production ? &#39;css/[contentHash].css&#39; : &#39;css/[id].css&#39;<br>    }),<br>    // Ejs pages<br>    ...generateHtml(pages)<br>  ]<br>}]</pre><pre>module.exports = config</pre><p>Webpack’s config is a JavaScript file. Keep in mind the above configuration is a generic configuration file suitable to me and my team. You can make changes to it according to your requirement. Let me explain the <strong>config</strong> array first.</p><p>config is an array of configurations. When running webpack, all these configurations are built. As we want only a single configuration we have a single object inside the array. The configuration object has the following fields: entry, output, module, resolve, optimization and plugins.</p><ul><li><strong>entry</strong>: This is the entry point for webpack from where it starts building the dependency graph. In the above config file, the value for this property is generated by the function generateEntryPoints. generateEntryPoints takes in the pages array. We follow a simple rule here: One entry point for each page. Function generateEntryPoints returns an object which for which keys are the elements and value are the path for the entry points. The output for the function will be something like:</li></ul><pre>{<br>  index : [&#39;./src/components/entrypoints/index.jsx&#39;]<br>}</pre><ul><li><strong>output</strong>: Sets the output path for the bundles based on the environment we are compiling for. Default is ./src/static/public. For NODE_ENV set to production output directory is ./dist/static/public.</li><li><strong>module</strong>: This property defines the rules on how each file in the dependency graph is resolved and loaders to be used for these files.<br>For JS and JSX files <a href="https://www.npmjs.com/package/babel-loader">babel-loader</a> has been used to transpile the code before it’s used for bundling.<br>For CSS, loaders used are MiniCssExtractPlugin.loader and <a href="https://www.npmjs.com/package/css-loader">css-loader</a>.<br>For EJS, it is using <a href="https://www.npmjs.com/package/raw-loader">raw-loader</a> to copy the text of the file for HTMLWebpackPlugin. <br>For images, it is using <a href="https://www.npmjs.com/package/file-loader">file-loader</a>.</li><li><strong>resolve</strong>: This is used here to configure in which order the modules with the same name but different extensions will be resolved.</li><li><strong>optimization</strong>: I’ve added here split chunk optimization to split pieces of code used by different entry point to chunks. So if two entry points share a module the module is added to a single chunk used by both the entry points.</li><li><strong>plugins</strong>: Plugins allow us to customize the build process. I’ve used 3 plugins here.<br>1. <a href="https://www.npmjs.com/package/html-webpack-plugin"><strong>HTMLWebpackPlugin</strong></a>: This plugin generates the ejs files for each entry point. The objects for this plugin is generated dynamically using the pages array by generateHTML function. For each page, an object of this plugin must be initialized. It takes the following options:<br> <em>chunk</em>:<strong> </strong>key for the entry point for each page.<br> <em>template</em>: A template ejs files path. A common template has been used in this project but separate templates can also be used.<br><em>filename</em>: The output files name from this instance of the plugin.<br>2. <a href="https://www.npmjs.com/package/mini-css-extract-plugin"><strong>MiniCSSExtractPlugin</strong></a>: This plugin is used to extract CSS imported in JSX files.<br>3. <a href="https://www.npmjs.com/package/clean-webpack-plugin"><strong>CleanWebpackPlugin</strong></a>: This is used to clean the output folder before every build.</li></ul><p>Note: <br>1. When building for the production environment all the emitted files’ file names will be their content-hash.<br>2. The HTMLWebpack plugin here takes care of adding the css file and js file references in the ejs file using the chunk option.</p><h3>Babel for Server-Side</h3><p>The above-mentioned config file is used by webpack to transpile code before bundling it. To transpile the JSX on server side we need to add a few more plugins. So I’ve created another config file called .babelrc.server.json. This file extends the .babelrc.json and a few extra plugins are added to it.</p><pre>{<br>  &quot;extends&quot;: &quot;./.babelrc.json&quot;,<br>  &quot;plugins&quot;: [<br>    [<br>      &quot;file-loader&quot;,<br>      {<br>        &quot;name&quot;: &quot;[hash].[ext]&quot;,<br>        &quot;extensions&quot;: [<br>          &quot;png&quot;,<br>          &quot;jpg&quot;,<br>          &quot;jpeg&quot;,<br>          &quot;gif&quot;,<br>          &quot;svg&quot;<br>        ],<br>        &quot;publicPath&quot;: &quot;/public/img&quot;,<br>        &quot;outputPath&quot;: null<br>      },<br>      &quot;img-file-loader-plugin&quot;<br>    ],<br>    [<br>      &quot;babel-plugin-transform-require-ignore&quot;,<br>      {<br>        &quot;extensions&quot;: [<br>          &quot;.css&quot;,<br>          &quot;.sass&quot;,<br>          &quot;.scss&quot;<br>        ]<br>      }<br>    ]<br>  ]<br>}</pre><p>The first plugin is <a href="https://www.npmjs.com/package/babel-plugin-file-loader"><strong>babel-plugin-file-loader</strong></a><strong> </strong>used here to change the images used using import e.g.: import image from &#39;./image.png&#39; to const image = &#39;/public/img/[filehash].png&#39; . What it is trying to do is convert the import statement to a initialise statement with the constant value as the public path on which image is served by the server.<br>The second plugin is <a href="https://www.npmjs.com/package/babel-plugin-transform-require-ignore"><strong>babel-plugin-transform-require-ignore</strong></a>. This is used to ignore css, sass and scss imports.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a88360f5667f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/server-side-rendering-using-react-and-express-part-2-a88360f5667f">Server-Side Rendering using React and Express — Part 2</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Server-Side Rendering using React and Express — Part 1]]></title>
            <link>https://medium.com/swlh/server-side-rendering-using-react-and-express-part-1-d1b54315cc55?source=rss-f8fcbcada017------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1b54315cc55</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[full-stack-development]]></category>
            <category><![CDATA[search-engine-optimizati]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Anshuman Chhapolia]]></dc:creator>
            <pubDate>Sun, 16 Feb 2020 06:00:55 GMT</pubDate>
            <atom:updated>2020-05-25T11:06:41.280Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*sGGiwo4fFXVGBAdVTan8bg.png" /></figure><h3>Server-Side Rendering using React and Express — Part 1</h3><h4>Implementing from scratch</h4><p>Server-Side Rendering lets us render a basic skeleton of our page server-side and send it to the user. This provides us with benefits like — Search engine optimisation and faster initial page load. You can clone this whole project from <a href="https://github.com/smoke-trees/ssr-react">here</a>. This is also available as a template on GitHub to start your project without setting up anything.</p><h3>Prerequisite</h3><p>Having experience in React and Express.js is a must for this. For Express you can visit <a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs">MDN tutorials on Express</a> and for React, <a href="https://reactjs.org/tutorial/tutorial.html">documentation</a> is the best place to learn. Please clone this project from GitHub. It has developer and production build scripts and config files. I’ll be covering about these in the next part. So it’s highly recommended you work on top of a clone of this repo.</p><h3>Project Directory Layout:</h3><pre>|-- project<br>    |-- .babelrc.json<br>    |-- .babelrc.server.json<br>    |-- package-lock.json<br>    |-- package.json<br>    |-- webpack.config.js<br>    |-- script.js    <br>    |-- src<br>        |-- server.js<br>        |-- components<br>        |   |-- entrypoints<br>        |   |     |-- index.jsx<br>        |-- pages<br>        |   |-- index.jsx<br>        |-- routes<br>        |   |-- index.js<br>        |-- views<br>        |-- |-- pages<br>        |   |   |-- template.ejs<br>            |-- partials</pre><h3>Understanding the files</h3><ul><li><strong>.babelrc.json</strong>: A config file for babel used for transpiling the code from JSX and ES2015+ to CommonJS understandable by Node.js</li><li><strong>.babelrc.server.json</strong>: Extra plugins added to Babel config required for the server-side code only.</li><li><strong>scripts.js</strong>: This file is the development server build script.</li><li><strong>webpack.config.js</strong>: Config file for the webpack. Webpack uses babel to transpile and then bundles our code for the browsers.</li><li><strong>server.js</strong>: This describes the express application and its routes.</li><li><strong>routes/index.js</strong>: Route handler is described here. This is the part where we render our React page into HTML to serve to the client.</li><li><strong>views/pages/template.ejs</strong>: The template ejs file. Webpack uses this file to generate ejs file with stylesheets and client-side code added to it.</li><li><strong>pages/index.jsx</strong>: Index page created using React.</li><li><strong>entrypoint/index.jsx</strong>: The entry point for the client-side code. What is an entry point?</li></ul><h3>How server-side rendering works?</h3><p>In Server-Side rendering, we use ReactDOMServer method render to string to render an initial HTML node for a page and serve this to the client as HTML. This rendered HTML also has client-side script embedded to it. The initial HTML is just a static page without any state or event handlers. The client-side script when ran will cause attach the event handlers to the rendered node. This processing of attaching Event Handlers is known as hydration. The above-mentioned <strong>entrypoint/index.jsx</strong> is the entry point for the client-side code where the hydrate function is called.</p><p>In this post, I’ll explain how you can write the route handler, create a Page using React, create an entry point for the client-side hydration.</p><h3>Create a new page</h3><p>At first, we create a file in the <strong>src/pages </strong>directory and let’s call it <strong>about.jsx</strong>. <br> To look at the final state of this project after adding the about page you can check out the <a href="https://github.com/smoke-trees/ssr-react/tree/tutorial">tutorial branch</a> of the project. We write our page as we will write a page to be displayed on React. We don’t need to use React Router as routing is handled by express here. We can include a stylesheet and images as we do in a <strong>create-react-app</strong> template.</p><p><strong>src/pages/about.jsx</strong></p><pre>import React, { Component } from &#39;react&#39;<br>import &#39;./about.css&#39;</pre><pre>export class About extends Component {<br>  render () {<br>    return (<br>      &lt;div className=&#39;heading&#39;&gt;<br>        This is the about page<br>        &lt;div className=&#39;subheading&#39;&gt;<br>          This is the sub heading<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    )<br>  }<br>}</pre><pre>export default About</pre><p>Create a stylesheet file <strong>about.css</strong> for this page. Add whatever styling rules you want to this file for this page. We can organise our files inside a directory inside the pages directory, just make sure to you write the correct reference path.</p><p>Now we write the entry point for the client-side. Create a file called <strong>about.jsx </strong>inside the <strong>src/components/entrypoints</strong>.</p><p><strong>src/components/entrypoints/about.jsx</strong></p><pre>import React from &#39;react&#39;</pre><pre>import { hydrate } from &#39;react-dom&#39;</pre><pre>import Index from &#39;../../pages/about&#39;</pre><pre>hydrate(&lt;Index /&gt;, document.getElementById(&#39;root&#39;))</pre><p>As we can see we call the hydrate method on a node with id root. Let us take a look at the <strong>views/pages/template.ejs</strong> file to get a better idea.</p><p><strong>views/pages/template.ejs</strong></p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt; <br>&lt;head&gt;<br>    &lt;title&gt;Smoke -h&lt;/title&gt;<br>&lt;/head&gt; <br>&lt;body&gt;<br>    &lt;div id=&quot;root&quot;&gt;&lt;%- reactApp %&gt;&lt;/div&gt;<br>&lt;/body&gt; <br>&lt;/html&gt;</pre><p>As we see the <strong>#root </strong>is the node which contains our initial rendered HTML. To see perform the initial rendering and serve the page we create a route handler. We create a file for the <em>/about the </em>route inside the <strong>src/routes</strong>. It’s a simple express route handler so you can create this file anywhere that suits you.</p><p><strong>src/routes/about.js</strong></p><pre>import express from &#39;express&#39;<br>import React from &#39;react&#39;<br>import { renderToString } from &#39;react-dom/server&#39;<br>import About from &#39;../pages/about&#39;</pre><pre>const router = express.Router()</pre><pre>router.get(&#39;/&#39;, async (req, res) =&gt; {<br>  const reactComp = renderToString(&lt;About /&gt;)<br>  res.status(200).render(&#39;pages/about&#39;, { reactApp: reactComp })<br>})</pre><pre>export default router</pre><p>As we see we render <strong>pages/about.ejs</strong> file that doesn’t exist now. This file will be created by webpack and will include the scripts required for hydration and bundled stylesheets. It will be as the same name as the entrypoint file. You can modify this behaviour by changing the config files yourself.</p><p>Now we need to add this route handler to the server.js file. After adding it to the file it should look something like this:</p><pre>import express from &#39;express&#39;<br>import compression from &#39;compression&#39;<br>import index from &#39;./routes/index&#39;<br>import about from &#39;./routes/about&#39;  <strong>//Line added here </strong><br>import path from &#39;path&#39;</pre><pre>// Server var<br>const app = express()</pre><pre>// View engine setup<br>app.set(&#39;views&#39;, path.join(__dirname, &#39;static&#39;, &#39;views&#39;))<br>app.set(&#39;view engine&#39;, &#39;ejs&#39;)</pre><pre>// Middleware<br>app.use(compression())<br>app.use(&#39;/public&#39;, express.static(path.join(__dirname, &#39;static&#39;, &#39;public&#39;)))</pre><pre>// Routes<br>app.use(&#39;/&#39;, index)<br>app.use(&#39;/about&#39;, about)  <strong>//Line added here</strong></pre><pre>const port = process.env.PORT || 3000</pre><pre>app.listen(port, function listenHandler () {<br>  console.info(`Running on ${port}`)<br>})</pre><p>Now we need to inform webpack that it needs to create a bundle for the about page and an ejs file for it. We can do this by adding a string with the same name as of the entry point file for the new page (without the extension) to the pages array in <strong>webpack.config.js</strong> file. After adding it the files look like:</p><pre>const path = require(&#39;path&#39;)<br>const HtmlWebpackPlugin = require(&#39;html-webpack-plugin&#39;)<br>const { CleanWebpackPlugin } = require(&#39;clean-webpack-plugin&#39;)<br>const MiniCssExtractPlugin = require(&#39;mini-css-extract-plugin&#39;)<br>const production = process.env.NODE_ENV === &#39;production&#39;</pre><pre>const pages = [&#39;index&#39;, &#39;about&#39;] <strong>//Add the string here</strong></pre><pre>const generateEntryPoints = (entry) =&gt; {<br>  return entry.reduce((obj, item) =&gt; {<br>    return {<br>      ...obj,<br>      [item]: [path.resolve(&#39;src&#39;, &#39;components&#39;, &#39;entrypoints&#39;, `${item}.jsx`)]<br>    }<br>  }, {})<br>}</pre><pre>const generateHtml = (entry) =&gt; {<br>  return entry.map((i) =&gt; {<br>    return new HtmlWebpackPlugin({<br>      chunks: [i],<br>      filename: `../views/pages/${i}.ejs`,<br>      template: path.join(&#39;src&#39;, &#39;views&#39;, &#39;pages&#39;, &#39;template.ejs&#39;)<br>    })<br>  })<br>}</pre><pre>const config = [{<br>  entry: {<br>    ...generateEntryPoints(pages)<br>  },</pre><pre>output: {<br>    path: production ? path.resolve(__dirname, &#39;dist&#39;, &#39;static&#39;, &#39;public&#39;) : path.resolve(__dirname, &#39;src&#39;, &#39;static&#39;, &#39;public&#39;),<br>    filename: production ? &#39;js/[chunkhash].js&#39; : &#39;js/[name].js&#39;,<br>    publicPath: &#39;/public&#39;<br>  },</pre><pre>module: {<br>    rules: [<br>      {<br>        test: /\.(js|jsx)$/,<br>        use: {<br>          loader: &#39;babel-loader&#39;,<br>          options: {<br>            presets: [&#39;<a href="http://twitter.com/babel/preset-env">@babel/preset-env</a>&#39;, &#39;<a href="http://twitter.com/babel/preset-react">@babel/preset-react</a>&#39;]<br>          }<br>        },<br>        exclude: [/node_modules/, /static/]<br>      }, {<br>        test: /\.ejs$/,<br>        loader: &#39;raw-loader&#39;<br>      }, {<br>        test: /\.(css)$/,<br>        use: [{<br>          loader: MiniCssExtractPlugin.loader,<br>          options: {<br>            publicPath: &#39;/public/css&#39;<br>          }</pre><pre>}, &#39;css-loader&#39;]<br>      }, {<br>        test: /\.(jpg|jpeg|png|svg|gif)$/,<br>        use: [{<br>          loader: &#39;file-loader&#39;,<br>          options: {<br>            name: &#39;[md5:hash:hex].[ext]&#39;,<br>            publicPath: &#39;/public/img&#39;,<br>            outputPath: &#39;img&#39;<br>          }<br>        }]<br>      }<br>    ]<br>  },</pre><pre>resolve: {<br>    extensions: [&#39;.js&#39;, &#39;.jsx&#39;, &#39;.json&#39;, &#39;.wasm&#39;, &#39;.mjs&#39;, &#39;*&#39;]<br>  },</pre><pre>optimization: {<br>    splitChunks: {<br>      automaticNameDelimiter: &#39;.&#39;,<br>      cacheGroups: {<br>        react: {<br>          chunks: &#39;initial&#39;<br>        }<br>      }<br>    }<br>  },</pre><pre>plugins: [<br>    new CleanWebpackPlugin(),<br>    // create blog,<br>    new MiniCssExtractPlugin({<br>      filename: production ? &#39;css/[contentHash].css&#39; : &#39;css/[id].css&#39;,<br>      chunkFilename: production ? &#39;css/[contentHash].css&#39; : &#39;css/[id].css&#39;<br>    }),<br>    // Ejs pages<br>    ...generateHtml(pages)<br>  ]<br>}]</pre><pre>module.exports = config</pre><p>This is enough to add a new page.</p><h3>Why not next.js?</h3><p>I as a developer want control over my code and the build scripts. In next.js it’s not possible. We can’t eject our app in next.js as we can do with <strong>create-react-app</strong>. If we want to access the config files we have to clone the whole next.js project and make the changes in config. Using next.js also forces us to maintain a file-structure to use the framework. On top of it, the application built can only be used to serve the frontend. While using this structure we can also implement a backend with frontend in the same project.</p><p>In the next part, I’ll explain the config files and the development server build script.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1b54315cc55" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/server-side-rendering-using-react-and-express-part-1-d1b54315cc55">Server-Side Rendering using React and Express — Part 1</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>