简体   繁体   中英

How does the JavaScript Import work under the hood?

How does the import statement actually work in JavaScript? I read the documentation and it says that it places exported code within the scope of the file. Does that mean that the code is copied over into the file where I type import?

For example - in library.js I have:

export {export function getUsefulContents(url, callback) {
    getJSON(url, data => callback(JSON.parse(data)));
}

In main.js I have:

import { getUsefulContents} from 'library.js';

getUsefulContents('http://www.example.com',
    data => { doSomethingUseful(data); });

This allows me to call getUsefulContents() in main.js. My question is, does main.js now have the contents that I exported from library.js?

Is using import the same as just having physically defined getUsefulContents() in main.js?

function getUsefulContents(url, callback) {
    getJSON(url, data => callback(JSON.parse(data)));
}

getUsefulContents('http://www.example.com',
    data => { doSomethingUseful(data); }); 

The main reason why I ask is because I want to know if using import will have an effect on main.js file size? Or is something else going on under the hood?

Thank you!

Depends on how you are using main.js . If you run it through a bundler, then the bundler will probably include library.js into main.js to pack it up into one file. In that case, the only advantage would be maintainability and ease of development because you are focused on the file you are working on. If you are simply running the import statement and deploying your application, the import statement won't affect the file size of main.js .

It just namespacing it within the file that you are importing it to so

any code from useful-library.js is included in the file, I visualize it this way

import { usefulCodeFromLibrary } from './useful-library.js'; 

((usefulCodeFromLibrary)=>{
  // My excellent code
  
  // Imported code doing it's job
  usefulCodeFromLibrary.someHelperFunction()
}()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM