0

I search on the Internet and it said that the difference between require and import is that require will call entire JS file. So in my situation, does entire module.js file will be called? And if it not, in which case that file will be called entirely ?

module.js

const a = 10;
const b = 20;
const c = 30;

module.exports = { a , b };

app.js:

const nums = require('./module');

console.log(nums);
  • 3
    `the difference between require and import is that require will call entire JS file` as opposed to??? where did you get this information? – Bravo Mar 02 '22 at 07:22
  • 2
    Since things can depend on other things in the file, the entire file will always be evaluated on import. You can’t just selectively evaluate individual lines from it but not others. – deceze Mar 02 '22 at 07:23
  • This is the reference : https://stackoverflow.com/questions/46677752/the-difference-between-requirex-and-import-x. When I scroll down, some one said that entire JS file will be called with require. His answer got 28 upvotes – Đoàn Đức Bảo Mar 02 '22 at 07:27
  • 4
    That is not a super accurate description, as has been noted in the comments. The highest voted answer there has over 500 upvotes, to put those 28 into relation… – deceze Mar 02 '22 at 07:41

1 Answers1

0

For some reason using the name module removed the code highlighting so I added the comments which fixed it....

In you example the entire module file is not loaded. And it is not correct to say that it can be. Module exports is not a file based module loader. Module functionality technically could be spread over many files. But, if you create a default and put everything in it that would be nearly the same thing.

(Assuming you are only using a single file to define your module.)

module.js

export const name = /** < **/ module /** name >**/;


export default  /** < **/ module /** name >**/;

You could then use named exports as before or using one of the import default syntax variations grab the entire file.

app.js

import /** < **/ module /** name> **/ from './modules.js';

or alternatively

import {default as /** < **/ module /** name> **/} from './modules.js';