JavaScript

What Is Webpack, What Is Used For?

Webpack is a bundle creator for our javascript files. It is a module bundler javascript library. One of big software projects’s problem is that it includes too many script src codes which provides including javascript libraries to our projects. These too many script src codes provide confusion and create spagetti code. Webpack solve this problem for us and it provides one javascript file (library) for adding to projects. If I will define this situation with an example, I can write codes below for it.

For example, our new javascript file (module) (e.g. newmodule.js) looks like that:

P.S: Javascript file has got only one “export default” property in a file. The other exports have to be “export“. The difference between export default and export is only that you should use ‘{‘ ‘}‘ tags before and after exported objects (functions, variables etc.) in a main javascript file (e.g.: index.js).

 //newmodule.js 

export default function NewModule() {
 //function context
 }

 export const name = 'Aytac';
 export const surname = 'AGMA'; 

Our main javascript file (e.g.: index.js) looks like below:

 //index.js

 import  NewModule from './newmodule';
 import {name} from './newmodule'; 

 NewModule(); 

 console.log(name);

Our webpack.config file looks like below. Entry property is our main javascript file (index.js) which includes import statements to other javascript files’s functions, variables etc. Output object has our goal file in the filename property, Webpack will create this file with this defined name (bundle.js).

//webpack.config

module.exports = {
    entry: './index.js',
    output: {
      filename: 'bundle.js'
    }
} 

As a result of all, you can see below, I have included only one script file instead of a lot of script files.

 <html>
  <head>
    ...
    <script src="bundle.js"></script> 
  </head>
  <body>
    ...
  </body>
</html> 

Have a good codings.. See you in other posts..

B. Aytac AGMA
Comp. Eng.

You can share and save this page with:
Tags: , , , , , , , , , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*