How to use index.php as the index file with create-react-app

Shailesh
5 min readMay 9, 2020

Recently I came across a scenario with a react app, where I had to use index.php as the index file instead of the usual index.html file due to some legacy configuration bootstrapping. Webpack by default, does not understand how to deal with php files and at the same time, did not want to lose the live reload capabilities that comes with webpack.

Let us see how this can be solved.

So we start with creating a react app using create-react-app

create-react-app apache-php-index-demo

We will be ejecting out of create-react-app for simplification, but you can still try out non ejecting ways to modify webpack configuration.

HtmlWebpackPlugin is a webpack plugin that is used under the hoods to generate the index.html file in create-react-app. It has a bunch of other functionality built in. Check out at https://github.com/jantimon/html-webpack-plugin

In create-react-app, public/index.html is used as the template for Html webpack plugin.

plugins: [
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin(
Object.assign(
{},
{
inject: true,
template: paths.appHtml,
},

...
]

HtmlWebpackPlugin uses this template index file, injects a scripts tag referencing webpack bundle( that gets generated during webpack build) and outputs an index.html and assets. It also hashes the bundle etc.

When running with webpack-dev-server, index.html and bundles are not written to disk but served from memory. Webpack dev server also injects piece of code into the bundle that is responsible for live reloading.

So Let’s try to use a index.php file as template index file.

Let us move the index.html from public directory to srcdir and rename it to index.php and modify appHtml value in config/paths.js file.

module.exports = {
dotenv: resolveApp('.env'),
appPath: resolveApp('.'),
appBuild: resolveApp('build'),
appPublic: resolveApp('public'),
appHtml: resolveApp('src/index.php'),

Running yarn start. we get the following error

Shailesh

Solving Problems. Making Software Better. Intrigued by Elegant Solutions. https://twitter.com/agent_hunt