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.

--

--

Shailesh

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