How to install Webpack to a PHP project

How to install Webpack to a PHP 8 project to compile sass files

Posted by Margie Crona on November 28, 2021

How to install Webpack to a PHP project

How to install Webpack to a PHP 8 project to compile sass files

Posted by Margie Crona on November 28, 2021

Webpack is a software tool that bundles all of your modules and dependencies that helps with front end development into one file which you can then include in your project. In this blog, I will explain to you how to set up Webpack for your PHP project.

In this example the Slim framework will be used, however you should be able to use any similar PHP project set up. Before we start the tutorial make sure you have Node.js installed on your computer.

Step 1. Go to your root and run command

npm init -y

The command npm init creates the package.json file.

The -y skips questions asked while npm init command is being executed.

You should see a file similar to below:

{
  "name": "wp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Step 2. install packages.

npm install

npm install -g webpack

npm install -g webpack-cli

npm install sass

npm install css-loader sass-loader file-loader --save-dev

Your package.json file should look like below after installing the packages and editing the script object:

{
  "name": "wp",
  "version": "1.0.0",
  "description": "",
  "main": "webpack.config.js",
  "scripts": {
    "start": "webpack-dev-server --mode=development",
    "build": "webpack --mode=production",
    "dev": "npm run development",
    "development": "webpack --mode=development",
    "watch": "webpack --watch --progress"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "html-webpack-plugin": "^5.4.0",
    "sass": "^1.43.3",
    "bootstrap": "^5.1.3"
  },
  "devDependencies": {
    "webpack": "^5.59.1",
    "webpack-cli": "^4.9.1",
    "sass-loader": "^12.2.0",
    "style-loader": "^3.3.1",
    "css-loader": "^6.4.0",
  }
}

The above object is just an example. You might want to install other packages and configurations based on what you want to do in your project.

Step 3. Manually create file webpack.config.js at root of project and add configuration below.

const path = require('path');

module.exports = {
    entry: ["./app/assets/sass/app.scss"],
    output: {
        path:path.resolve(__dirname, "./public/assets/js"),
        filename: 'app.js'
    },
    module: {
        rules: [
            {
                test: /\.(scss|css)$/,
                use: ['style-loader', 'css-loader', 'sass-loader'],
            },
            {
                test: /\.(png|jp(e*)g|svg|gif)$/,
                use: ['file-loader'],
            },
            {
                test: /\.svg$/,
                use: ['@svgr/webpack'],
            },
        ]
    },
    devServer: {
        static: path.join(__dirname, "/")
    }
}

The path const that holds require is Node.js global function that allows you to extract contents from module.exports object.

The module.exports is an object that allows the contents within to be available publicly.

The entry property value in module.exports tell webpack which file(s) it needs to bundle.

The output property defines where it needs to output the bundled file.

The rules property object within the module property object of how webpack will take our files, compile and bundle them for the browser. In the case above you are able to bundle CSS, SCSS, SVG and some image types.

The devServer property object is used to tell what file to serve, in other words once you run npm run dev the entry file(s) will be bundle. The app.js indicated in output will be created and the bundle will be placed in that file and that file placed in the directory indicated in the static property path within devServer. 

Step 4. Add a directory called app at the root of your project and with that directory create another called assets within the assets directory, create another called sass.

You do not have to lay out your file structure in this way. However, make sure within file webpack.config.js the entry property value within module.exports has the correct path.

Step 5. Within sass directory create 2 files, one called _home.scss and another app.scss.

enter the below script for _home.scss:

h1{
  color:red;
  &:hover{
    color:green;
  }
}

enter the below script for app.scss:

@import "~bootstrap/scss/bootstrap";

@import "home";

Step 6 . In your public directory, create assets directory and within assets directory create a js directory.

Again, the file structure does not have to be this specific layout. However, make sure within file webpack.config.js the output property value within module.exports has the correct path.

Step 7. Add the path of the app.js file that will contain the compiled scss files in the header of your project or in the header of the page you want the scss styling to be. This file will be in a public folder. The next step will create app.js.

<script src="<?= $baseUrl; ?>assets/js/app.js"></script>

Step 8. execute npm run dev 

This execution will create the app.js file in public/assets/js

You can run npm run watch, so any time you change the _home.scss file, compilation will happen automatically.

Make sure you do hard refresh after every file change and compilation.

The project structure is here:

Download project here

Please run npm install within project root, if you plan to download the project above.

That is it! Hopefully you now have some understanding of setting up Webpack in your PHP project.

Here is the follow up tutorial on how to install react to what we have so far Install React to your PHP project