🎉 ARTICLE UPDATED:
webpack ^5.82.1 webpack-cli ^5.1.1 webpack-dev-server ^4.15.0
In the world of modern web development, webpack has earmarked its reputation and become 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 to 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
- You must be familiar with npm CLI & package.json
- I assume you have a basic knowledge of Webpack.
- You have Node Environment setup to run the NPM commands.
- Your local server (localhost) is also ready.
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 on 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 the below command.
npm i -D webpack webpack-cli webpack-dev-server
Update package.json
to add a start
the 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 { join } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
target: 'web',
mode: 'development',
devServer: {
devMiddleware: {
publicPath: join(__dirname, 'build'),
writeToDisk: true,
},
hot: false,
port: '8989',
proxy: {
'/': {
target: `http://localhost/webpack-devserver-php/dist`,
},
},
static: false,
watchFiles: ['src/**/*.*', 'app/**/*.*'],
},
};
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 phpinfo(); ?>
</body>
</html>
Update webpack.config.js
file with the following lines of code.
...
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
...
entry: {
index: join(__dirname, 'src/index.js'),
},
plugins: [
new HtmlWebpackPlugin({
template: 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 an illogical thing anymore. If you have a better configuration to work with PHP & Webpack 5 do share in the comments below.
Hello! Thank you for this useful code snippet.
Unfortunately it doesn’t work with the current version of Webpack. You can modify the devServer configuration to this and it should work:
I also need to add ‘changeOrigin: true’ to prevent an 404 error.
devServer: {
host: ‘localhost’,
port: 8989,
proxy: {
‘*’: {
target: `http://localhost/webpack-devserver-php/dist`,
changeOrigin: true
},
},
devMiddleware: {
publicPath: path.resolve(__dirname, ‘dist’),
writeToDisk: true,
},
},
Hi, I have updated the article to support webpack-dev-server 4. Please check and try again.
Congratulations, great job. But with webpack-dev-server version 4 I get errors:
[webpack-cli] Invalid options object. Dev Server has been initialized using an options object that does not match the API schema.
– options has an unknown property ‘writeToDisk’. These properties are valid:
object {allowedHosts ?, bonjour ?, client ?, compress ?, devMiddleware ?, headers ?, historyApiFallback ?, host ?, hot ?, http2 ?, https ?, ipc ?, liveReload ?, magicHtml ?, onAfterSetupMiddleware ?, onBeforeSetupMiddleware ?, onListening ?, open ?, port ?, proxy ?, server ?, setupExitSignals ?, setupMiddlewares ?, static ?, watchFiles ?, webSocketServer? }
Hi, I have updated the article to support webpack-dev-server 4. Please check and try again.
This is unfortunately out of date. The current devServer does not support the used options. Would be great, if you could update this article accordingly.
I will soon update this article for Webpack 5 & PHP 8
Hi Kumar! Thanks for making avaible this configuration.
Were you able to write an updated configuration for Webpack 5 & PHP 8?
Hi, I have updated the article to support webpack-dev-server 4. Please check and try again.
great job,
thanks
Thank you 👍