How to package NodeJs application using Webpack

How to package NodeJs application using Webpack

Hi guys, in this article we are going to know about Bundling NodeJs Application using Webpack. During our Production build, we require the file sizes to be as tiny as likely to improve app loading and usage speed...

Hi guys, in this article we are going to know about Bundling NodeJs Application using Webpack. During our Production build, we require the file sizes to be as tiny as likely to improve app loading and usage speed. We also require there to be as few files as possible to decrease the number of request calls of the server and also we want to minify and uglify our written source code, with comments and blank space removed. We also require to encode static images directly into our HTML files.

To bypass unwanted imports and to keep Development and Production thoughts separate, we will have a separate Express server file for Development and Production, and separate Webpack config files for Development and Production our node application code, and for the server also.

Step 1: Install nodejs in your system / Make workspace directory

Let’s begin from scratch with a new folder and run the following command to make a new folder and package.json file.


mkdir webpack_demo
 
cd webpack_demo
 
npm init --yes

Step 2: Install required packages using NPM

Here we need to install required dependency packages using the following commands. This package installs as a DEV dependency.

npm i -D webpack webpack-cli

Step 3: Create the required folders

Now we need to create “src” folder inside of our application because of the Webpack default entry point as “src” folder. Create index.html and main.js file once the source folder had been created in our working directory.


 mkdir src

 touch main.ts

 touch index.html



Step 4: Basic Bundling process

Run the following command to generate a bundling file from our source code. This command will commple our source code and create bundle files into the dist folder.


webpack <entry> [<entry>] -o <output>


webpack src/index.js -o dist/main.js


Step 5: Adding Script / Command

Add build command on script section in package.json file and it helps us to use lang command with a single keyword.



"build": "webpack <entry> [<entry>] -o <output>",

"build": "webpack src/index.js -o dist/main.js",


Step 6: Webpack bundle mode

Bundling mode help us to define what kind of file comprestion is reuired to production and development process. We can add this property using mode parameter in webpack command.



  
   -d (or) --mode development // It wont minify the script

   -p (or) --mode production // It will minify the script


Step 7: Webpack Config file setup

Webpack is a zero-configuration setup process but we can config some basic and relevant details for the bundling process. Using this file we can define entry point, destination path, bundle file name, module, and rule for bundling process. It also helps us to define multiple configurations files for a different mode of bundling like dev or prod.

  • entry -> Entry point for Webpack src file
  • output -> It helps us to configure output files
  • mode -> Bundling mode like dev or production

touch webpack.config.js



const path = require("path");

module.exports = {
    entry: './src/index.js',
    output: {
        path: path.join(__dirname, 'dist'),
        filename: 'main.[hash].js'
    },
}


Step 8: Bundling & Copy HTML file to the dist folder

Here we need to move the HTML file to the dist folder for the production build test. Basic Webpack command will process the entry JS file and move the bundled JS file to the dist folder. To do this operation we need the following package and install as a dev dependency.


npm i -D html-webpack-plugin html-loader


Once the package has been installed in our working directory we need to add the rule and plugins for the HTML files process.



.....
.....

const HtmlWebpackPlugin = require("html-webpack-plugin");

.....
.....

module.exports = {
    entry: './src/index.js',
    output: {
        path: path.join(__dirname, 'dist'),
        filename: 'main.[hash].js'
    },

    module: {
        rules:[
        ....
        ....
            {
                test: /\.html$/,
                use: [
                   {
                        loader: "html-loader",
                        options: { minimize : false }
                    }
                ]
            },
        ....
        ....
        ]
    },
    plugins: [
        ....
        ....
        new HtmlWebpackPlugin({
            template: "./src/index.html",
            filename: "./index.html"
        }),
        ....
        ....
    ]
}


Step 9: Bundling & Copy JS file to dist folder using babel-loader

Here we need to add the rule for JS files compression and it uses bable-loader for syntax check and file minimization. Here we exclude node_modules director for JS file compression. For this, we need the following packages and install as a dev dependency


npm i -D @babel/core babel-loader @babel/preset-env


Once the package has been installed in our working directory we need to add the rule for the JS files process.



....
....

module.exports = {

    module: {
        rules:[
            ....
            ....
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            },
            ....
            ....

        ]
    },
}



Step 10: webpack-dev-server configuration

Webpack dev server helps a lot while development time. It will compile source code and keep it as in temporary cache path. It won’t create any dist folder on the working directory instead of this it will produce a URL path to access the laster compiled code. Using this dev server we can check our code modification as instantly into the browser. The following package is required for dev server configuration and installs as a dev dependency.


npm i -D webpack-dev-server


Add script in package.json file,



  "scripts": {
    .....
    .....
    "webpack:dev": "webpack-dev-server"
    .....
    .....
  },


Step 11: Bundling & Copy Image file to dist folder

Most of the time we include some static files into our HTML pages like images. While normal Webpack compile process it won’t move to the dist directory. For this, we need to include the following packages and install them as a dev dependency in the working directory. This package will generate new images with a hashed file name and move to the dist folder and update the HTML file with relevant file names automatically.


npm i -D file-loader


Once the package has been installed in our working directory we need to add the rule for the Static files process.


....
....

module.exports = {

        rules:[
            ....
            ....
            {
                test: /\.(png|jpg|svg|gif)$/,
                use: [
                   {
                        loader: "file-loader",
                    }
                ]
            },
            ....
            ....
        ]
    },
    
}


Step 12: Bundling & Copy SCSS file to dist folder

In major applications have style details for there components. For this, we use Style files and corresponding details writing inside of it. While loading the HTML file corresponding style components also loaded with it. For adding style component into our dist folder we need the following packages and install as a dev dependency.

npm i --save-dev css-loader style-loader sass-loader node-sass

After the packages have been installed we need to add the rule for the Style files process.



module.exports = {
    ....
    ....

    module: {
        rules:[
            ....
            ....
            {
                test: /\.scss$/,
                use: [
                     "css-loader",
                     "sass-loader"
                ]
            },
        ]
    },
    ....
    ....
}


The above code helps us to compile the SCSS file to the CSS file and minifying the CSS file to the uglify file. After it includes the style input as a normal JS script into the HTML file. It won’t create any separate CSS file for application style.



module.exports = {
    ....
    ....

    module: {
        rules:[
            ....
            ....
            {
                test: /\.scss$/,
                use: [
                    "style-loader",
                     "css-loader",
                     "sass-loader"
                ]
            },
        ]
    },
    ....
    ....
}


Step 13: Include compiled SCSS as CSS file into index HTML file

For adding separate style files and include into HTML we need the following package for CSS extract. We need to install the following package as a dev dependency.


 npm i -D mini-css-extract-plugin


After package gets installed we need to include a plugin code in the Webpack config file and also we need to include extract loader in the SCSS rule loader list.



const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
    ....
    ....

    module: {
        rules:[
            ....
            ....
            {
                test: /\.scss$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    //  "style-loader",
                     "css-loader",
                     "sass-loader"
                ]
            },
        ]
    },
    ....
    ....
    plugins: [
        ....
        ....
        new MiniCssExtractPlugin({
            filename: "[name].[hash].css",
            chunkFilename: "[id].[hash].css"
        })
        ....
        ....
    ]
}


Step 14: Cleaning old file in the dist folder

Most of the time we run the bundling process for code changes and any file content changes for production deployment. At that time we need to clear the old build folder or director for fresh code. It mandatory for old content replaces with new content. To avoiding cache and extra file process we want to do the above operations. For this, the following package helps us to clear the old dist folder and create a new file component for the new build process. We need to install the following package as a dev dependency.


npm install --D clean-webpack-plugin


After completion of the above process, we need to include a new plugin with Webpack config plugin array. It always runs clear command before the new bundling process.



....
....
const {CleanWebpackPlugin} = require("clean-webpack-plugin");

module.exports = {
    ....
    ....
    plugins: [
        new CleanWebpackPlugin(),
    ]
}


Here the complete webpack config file details.



const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const {CleanWebpackPlugin} = require("clean-webpack-plugin");

module.exports = {
    entry: './src/index.js',
    output: {
        path: path.join(__dirname, 'dist'),
        filename: 'main.[hash].js'
    },

    module: {
        rules:[
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            },
            {
                test: /\.html$/,
                use: [
                   {
                        loader: "html-loader",
                        options: { minimize : false }
                    }
                ]
            },
            {
                test: /\.(png|jpg|svg|gif)$/,
                use: [
                   {
                        loader: "file-loader",
                    }
                ]
            },
            {
                test: /\.scss$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    //  "style-loader",
                     "css-loader",
                     "sass-loader"
                ]
            },
        ]
    },
    plugins: [
        new CleanWebpackPlugin(),
        new HtmlWebpackPlugin({
            template: "./src/index.html",
            filename: "./index.html"
        }),
        new MiniCssExtractPlugin({
            filename: "[name].[hash].css",
            chunkFilename: "[id].[hash].css"
        })
    ]
}


That’s all we already have done all required component rules and plugins for HTML, JS, Static Files, SCSS, and Cleanup process. Now we are ready to do a build process for all kinds of environment deployment.

Thanks for reading !

Originally published at learninfinity.info

Node.js for Beginners - Learn Node.js from Scratch (Step by Step)

Node.js for Beginners - Learn Node.js from Scratch (Step by Step)

Node.js for Beginners - Learn Node.js from Scratch (Step by Step) - Learn the basics of Node.js. This Node.js tutorial will guide you step by step so that you will learn basics and theory of every part. Learn to use Node.js like a professional. You’ll learn: Basic Of Node, Modules, NPM In Node, Event, Email, Uploading File, Advance Of Node.

Node.js for Beginners

Learn Node.js from Scratch (Step by Step)

Welcome to my course "Node.js for Beginners - Learn Node.js from Scratch". This course will guide you step by step so that you will learn basics and theory of every part. This course contain hands on example so that you can understand coding in Node.js better. If you have no previous knowledge or experience in Node.js, you will like that the course begins with Node.js basics. otherwise if you have few experience in programming in Node.js, this course can help you learn some new information . This course contain hands on practical examples without neglecting theory and basics. Learn to use Node.js like a professional. This comprehensive course will allow to work on the real world as an expert!
What you’ll learn:

  • Basic Of Node
  • Modules
  • NPM In Node
  • Event
  • Email
  • Uploading File
  • Advance Of Node

How to get started Internationalization in JavaScript with NodeJS

How to get started Internationalization in JavaScript with NodeJS

Tutorial showing how to use the Intl JS API in NodeJS (i18n). We'll install a module to unlock the Intl API languages for Node and test out RelativeTimeFormat to translate and localise relative times in JavaScript.

Tutorial showing how to use the Intl JS API in NodeJS (i18n). We'll install a module to unlock the Intl API languages for Node and test out RelativeTimeFormat to translate and localise relative times in JavaScript. I'll tell you how to get started with the built-in internationalization library in JS for Node 12 and higher. We'll change the locale to see how the translation works and test different BCP 47 language tags.

Internationalization is a difficult undertaking but using the Intl API is an easy way to get started, it's great to see this new API in the JS language and available for use. Soon, you'll be able to have confidence using it in the browser as modern browsers support the major Intl features. Have a look at the browser compatibility charts to see which browsers and versions of node are supported.

Use Intl.RelativeTimeFormat for language-sensitive relative time formatting.
#javascript #nodejs #webdevelopment

MDN Documentation:

https://developer.mozilla.org/en-US/d...

Full ICU NPM package:

https://www.npmjs.com/package/full-icu

What is WebAssembly? What does it mean for JavaScript and Node.JS?

What is WebAssembly? What does it mean for JavaScript and Node.JS?

What is WebAssembly? Is it going to replace JavaScript?! Signs say no, but it still has the potential to have a huge impact on JavaScript development in the browser and in Node.JS.

WebAssembly has been around for years but is only just starting to gain real traction in the developer space. What is WebAssembly? Is it going to replace JavaScript?! Signs say no, but it still has the potential to have a huge impact on JavaScript development in the browser and in Node.JS. Let’s walk through the how and why of this amazing new language feature through code and discussion.

Speaker: Mx Kassian Wren | DevRel, Cloudflare.

--

WebAssembly and the future of Web development

WebAssembly (abbreviated Wasm) is a binary instruction format for a stack-based virtual machine. Wasm is designed as a portable target for compilation of high-level languages like C/C++/Rust, enabling deployment on the web for client and server applications.

WebAssembly gives developers a way to write optimized code routines, usually in C++. This is powerful ability, but it has a relatively narrow scope. It’s useful if you need to improve the performance of complex calculations. (For example, fastq.bio used WebAssembly to speed up their DNA sequencing calculations.) It’s also important if you’re porting high-performance games or writing an emulator that runs inside your browser. If this is all there were to WebAssembly, it wouldn’t be nearly as exciting — and it wouldn’t have any hope of displacing JavaScript. But WebAssembly also opens a narrow pathway for framework developers to squeeze their platforms into the JavaScript environment.

Here’s where things take an interesting turn. WebAssembly can’t sidestep JavaScript, because it’s locked into the JavaScript runtime environment. In fact, WebAssembly needs to run alongside at least some ordinary JavaScript code, because it doesn’t have direct access to the page. That means it can’t manipulate the DOM or receive events without going through a layer of JavaScript.

This sounds like a deal-breaking limitation. But clever developers have found ways to smuggle their runtimes in through WebAssembly. For example, Microsoft’s Blazor framework downloads a miniature .NET runtime as a compiled WASM file. This runtime deals with the JavaScript interop, and it provides basic services (like garbage collection) and higher-level features (layout, routing, and user interface widgets). In other words, Blazor uses a virtual machine that lives inside another virtual machine, which is either an Inception-level paradox or a clever way to create a non-JavaScript application framework that runs in the browser.

Blazor isn’t the only WebAssembly-powered experiment that’s out of the gate. Consider Pyodide, which aims to put Python in the browser, complete with an advanced math toolkit for data analysis.

This is the future. WebAssembly, which started out to satisfy C++, Rust, and not much more, is quickly being exploited to create more ambitious experiments. Soon it will allow non-JavaScript frameworks to compete with JavaScript-based standbys like Angular, React, and Vue.

And WebAssembly is still evolving rapidly. It’s current implementation is a minimum viable product — just enough to be useful in some important scenarios, but not an all-purpose approach to developing on the web. As WebAssembly is adopted, it will improve. For example, if platforms like Blazor catch on, WebAssembly is likely to add support for direct DOM access. Browser makers are already planning to add garbage collection and multithreading, so runtimes don’t need to implement these details themselves.

If this path of evolution seems long and doubtful, consider the lessons of JavaScript. First, we saw that if something is possible in JavaScript, it is done. Then, we learned that if something is done often enough, browsers make it work better. And so on. If WebAssembly is popular, it will feed into a virtuous cycle of enhancement that could easily overtake the native advantages of JavaScript.

It’s often said that WebAssembly was not built to replace JavaScript. But that’s true of every revolutionary platform. JavaScript was not designed to replace browser-embedded Java. Web applications were not designed to replace desktop applications.