How To use Webpack for Frontend inside your Express.js Project - torok-technology torok-technology: How To use Webpack for Frontend inside your Express.js Project

recent

all you want in technology

Post Top Ad

Post Top Ad

Saturday, 28 July 2018

How To use Webpack for Frontend inside your Express.js Project



Hello everyone, welcome back in a new small node.js and javascript tutorial to explain to you how can you use Webpack for your javascript frontend code with express.js as a node.js serverside framework without needing to run Webpack and express.js on different ports, so let us start.

firstly you need to install node.js on your machine, you can download it from the official site.

And after installing it you need to download The Express.js globally to generate it in anytime from everywhere on your machine, so open the command line and go to your C drive and write this command:


npm install --save express -g

After that in your cmd you can navigate to any folder you want to start the project.And to generate express automatically with the needed packages and functions you can just write in the command line "express containerFolderName" and by default, it generates the application with ejs as a template engine but if you want to change it to another one you can write as the following: "express --view=engineNameHere containerFolderName" so I ma choosing handlebars as a template engine for this project and my container folder will be called newApp so I will write this command as the following:



express --view=hbs newApp

And it automatically creates the default express.js project to help you run your program faster


and then navigate with the cmd to the folder project which created. Now you need to install all dependencies which added by the express generator so to accomplish that just write this command in cmd

npm install

now to test the scratched app try to run it.
Note: in the express app to run your project will run a file called www existed inside bin folder and this file has all configuration of the project like the port and the type of environment is production or development and things like that, so to run your program you can write like that and then hit enter


node ./bin/www

Now try to open the browser and navigate to localhost:3000 to test your project and now you have this screen :


and this is the structure of your app right now

so now we need instead of rerun the application after any change manually, there is a good package does this mission perfectly called Nodemon so let's install it.
to do that write in the command line this command an hit enter

npm install --dev nodemon

and the package will be installed in the application ad a development dependency.

so now we need to edit the package.json file to make nodemon work in a proper way. In the package.json file, you can look to scripts object inside this object you can add many scripts allow you run the program and do many tasks before running it so we will add a new script will call it build and this script will b to run the www file so I will write like that:
{
"name": "newapp",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www",
"build": "nodemon ./bin/www"
},
"dependencies": {
"body-parser": "~1.17.1",
"cookie-parser": "~1.4.3",
"debug": "~2.6.3",
"express": "~4.15.2",
"hbs": "~4.0.1",
"morgan": "~1.8.1",
"nodemon": "^1.18.3",
"serve-favicon": "~2.4.2"
}
}

and then when you want to run the program you can hit in the command line npm run build and it will run the application automatically.

Now the last thing is coming now, we need to start working with webpack, maybe someone asking now why webpack! ??
sp the answer is: suppose you want to write an ES6 Javascript code for frontend doesn't provided natively in the browsers like import and export features so you can use webpack to manage that which bundles your js files in one file and you call this bundled file in your HTML page. some people use webpack and webpack dev server to run the frontend of application on a separated port and the express.js server on another port but what we need is keep running both on the same port without using webpack dev server, so firstly we will install webpack as the following command:



npm install --dev webpack --save

After installing webpack we should create webpack,config.js file which will contain all the configuration of bundled files os the basic configuration as the following:

const path = require("path");
module.exports = {
entry: "./public/javascripts/src/root.js",
output: {
path: path.resolve(__dirname, "public/javascripts/dist"),
filename: "bundle.js"
}
}

so firstly we require the path module of node.js and then we write module.exports to export this function to webpack package to processes and runs this file. Inside this module. exports object we define the entry property which means the entry point file which we wanna to bundle it and for that I made a folder called src inside the public/javascripts folder and inside it I made a js file called root.js and the output object refers to the file which we wanna put the bundled code inside it and for that we define two properties, the first one is the path of file and the second property is for the name of file. I made a folder inside public/javascripts called dist and when the webpack works it automatically will create a javascript file inside this path will be called bundle.js

Now inside the views dirctory, you can navigate to layout.hbs file and write a script tag and define its src to the src of bundle.js file like the following


<!DOCTYPE html>
<html>
<head>
<title>{{title}}</title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
{{{body}}}
<script src="./javascripts/dist/bundle.js"></script>
</body>
</html>

To run the webpack and bundle the root.js file you need to write this command

npx webpack --config webpack.config.js

and for the first time it will suggest to you to install webpack-command package or webpack-cli package to run this command so you can choose webpack-command and it will be installed.
After that you will need to wrote some es6 javascript code to test it so I will go to src folder and create a new js file and I will name it as app.js and I am putting a small js function which writes my name inside the dom as the following:

const myFunc = (name) => {
document.body.querySelector("h1").textContent = name;
}

and then I will export this function to root.js file which will contains all exported files

export {myFunc}



and inside the root.js file, I will import this function as the following


  import {myFunc} from "./app";


and run the function after importing it

import {myFunc} from "./app";

myFunc("tarek");



Then you can write the command again to bundle the root.js file as the following :

npx webpack --config webpack.config.js

and then run the server with this command

 npm run build


then refresh the browser and you will see this



It is amazing. Now Now what we need is bundling root.js when we start the server so to do that inside the package.json file inside the scripts object we will change the property of build key to the next code:


"build": "npx webpack --config webpack.config.js && nodemon ./bin/www"



 Now Webpack works good but we have a small issue while we develop the project, this issue is you need to close the server and re4start it again after any change happens in js frontend files because the webpack alone doesn't rebundle the root.js file after every change so we need to customize nodemon to accomplish this matter. So nodemon you can make your custom configuration for it and do that you need to make a new file called nodemon.json and automatically nodemon will process and runs the configurations inside it. After creating the nodemon json file you have to write the configuration inside t in object form but before writing anything we need to know what we want. By default nodemon restarts after every change happens in any file inside the whole project and that is great so we want to tell nodemon before restart "Hey we want to write a command before restarting" so to do that there is an events object which contains restart property and you can write inside it some commands you want to run before restarting so we can write the following configuration:

{
"events": {
"restart": "npx webpack --config webpack.config.js && npx webpack
--config webpack.adminconfig.js"
}
}

this is great but with this code, only nodemon will not work good cuz it will wait until write this command and after writing this command webpack will bundle the root.js file so roo.js file will be updated so nodemon will restart itself and it will still loop this process and go in infinite loop so to avoid that we need to add another property to nodemon.json file called ignore and this property tells nodemon to ignore array of files from watching so we need make nodemon ignore watching bundlejs file so the nodemon.json file will be as the following:

{
"ignore": [
"bundle.js"
],
"events": {
"restart": "npx webpack --config webpack.config.js && npx webpack
--config webpack.adminconfig.js"
}
}

So now you can start the application and while developing webpack will bundle the targeted js files
once you save and nodemon will restart the project automatically.
Now you have a perfect basic express.js and webpack web app project you can scale it as you want without any issues, so hopefullly you enjoyed with this tutorial and done't forget to purt your comment bellow if you have any issue and I will help you, thank you.


No comments:

Post a Comment

Post Top Ad