Home > Back-end >  What is the difference between a js file and a js module?
What is the difference between a js file and a js module?

Time:10-24

I tried to search, but cannot find precise / concise answer to this question. It appears to be used loosely and interchangeably, IMO. Anyone can teach me?

CodePudding user response:

Well we can get really technical here.

A file is anything on an OS that can handle IO information storage, of which there are various types i.e. text files and directories. A directory is a specific type of file that allows other files to be stored within.

When you speak about a "js file" it's sort of slang for "a text file that has a .js extension and javascript within".

In modern javascript modules are used to create more cleanly separated and reusable modular pieces of code, which can be exported and imported into other modules (technically files). They're sort of like namespaces in other languages (not really but sort of) but each file can only have a single namespace (module).

You can also have js files that are not modules, all modules are files but not all files are modules.

CodePudding user response:

Good question!

Background: JavaScript files used to be very small but as the JavaScript language has become more popular, the JavaScript files have become so large that "modules" were introduced to to help break up the JavaScript code into smaller, more manageable pieces.

So what does this mean?

Simply put, a module is a javascript file that has been structured into a smaller, more manageable file size.

Here is a article on MDN Web Docs that goes into greater detail:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules

In the example below main.js is a javascript file that is not a module, but both canvas.js and square.js are javascript modules. All 3 are javascript files but canvas and square are broken out into their own files to be more manageable.

Example:
index.html
main.js
modules/
canvas.js
square.js

Image of above example

Here is a link to the code on Github for the example above: https://github.com/mdn/js-examples/tree/master/modules/basic-modules

  • Related