Scroll to top
configurewebpack5devserverwithaphpwebsitehostedonlocalhost
Go to Blog Page Published / May 08, 2021

Configure Webpack 5 devServer with a PHP website hosted on localhost.

Configure Webpack 5 devServer with a PHP website hosted on localhost.

In the world of modern web development, webpack has earmarked its repute and became quite a popular technology. On the other hand, if you are a freelancer (like me) you cannot avoid PHP due to its demand and supply. Getting Webpack 5 and PHP work together sounds like an illogical thing to many.

Eventually, I figured out an approach to make these two well know beasts work together and without a doubt, they have a great blend. 2 major benefits of this approach are:

  • You get to use Webpack 5 with your PHP project resting in your localhost.
  • Experience Live Reloading while developing.

Without further ado, let’s figure out how we can configure Webpack 5 devServer with a PHP website hosted on localhost. You could download the final code from this GitHub Repo.

Prerequisites

Let’s get started!

Start your local server (localhost), I’m using MAMP for my local server environment. You can use XAMPP, WAMP, or the one you prefer the most. Create a directory of your project in your local server, I would name it webpack-devserver-php, you can name it whatever you like.

Open your preferred terminal and run the below command to create a default package.json file.

npm init -y # creates package.json file with default config

Continue with installing webpack, webpack-cli & webpack-dev-server by using below command.

npm i -D webpack webpack-cli webpack-dev-server

Update package.json to add a start script that runs the webpack serve command.

"scripts": {
  "start": "webpack serve"
}

We have successfully managed to configure the package.json file and installed webpack and its dependencies. Now, create webpack.config.js in the root directory of your project and add the following lines of code to it.

const path = require('path');

module.exports = {
  target: 'web',

  mode: 'development',

  devServer: {
    // Specifying a host to use
    host: 'localhost',

    // Specifying a port number
    port: 8989,

    // This is the key to our approach
    // With a backend on http://localhost/PROJECTNAME/
    // we will use this to enable proxying
    proxy: {
      // Star(*) defines all the valid requests
      '*': {
        // Specifying the full path to the dist folder
        // Replace "webpack-devserver-php" with your project folder name
        target: `http://localhost/webpack-devserver-php/dist`,
      },
    },

    // Bundle files will be available in the browser under this path
    publicPath: path.resolve(__dirname, 'dist'),

    // It writes generated assets to the dist folder
    writeToDisk: true,
  },
};

It’s a lot to grasp, right? Don’t fret, just follow the comments to understand the behavior of above code. A very important point to note is the devServer configuration that matters.

Let’s cover the remaining steps of our setup. Create a src folder inside the root directory of the project and add index.js & index.php files inside the src directory. Once all the files are in place, we need a PHP template page that would automatically bring in the bundled script and live-reload the page whenever there is a change within the project directory.

We’ll create a PHP template with html-webpack-plugin. Install the required plugin.

npm i -D html-webpack-plugin

Add basic HTML & PHP to the index.php file within the src folder.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Webpack 5, PHP & Live Reload</title>
</head>
<body>
<?php
  function displayInfo() {
    return phpinfo();
  }
  displayInfo();
?>
</body>
</html>

Update webpack.config.js file with the following lines of code.

...
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  ...

  entry: {
    index: path.join(__dirname, 'src/index.js'),
  },

  plugins: [
    new HtmlWebpackPlugin({
      template: path.join(__dirname, 'src/index.php'),
      chunks: ['index'],
      filename: 'index.php',
    }),
  ],
};

That’s all, now run the webpack serve command and open http://localhost:8989 on your browser.

npm start # starts webpack-dev-server as configured in package.json file

You would see PHP info displayed on your screen. For the fun part, make some changes in the src directory or src/index.php file and experience live-reloading.

We have successfully configured Webpack 5 devServer with a PHP website hosted on our local server (localhost). Now we can easily work with PHP projects and take full advantage of webpack alongside. I Hope, this blend is no more illogical thing anymore. If you have a better configuration to work with PHP & Webpack 5 do share in the comments below. Have a nice day!