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!
The import statement in JavaScript allows you to include code from other modules in your code. When you use the import statement, the exported code from the other module is not physically copied over into the file where you type the import statement. Instead, the exported code is made available within the scope of the file that imports it.
In your example, when you use the import statement in main.js:
import { getUsefulContents} from 'library.js';
The code from library.js is not physically copied over into main.js. Instead, the getUsefulContents function is made available in the scope of main.js, so you can use it just as if it were defined in main.js.
Using the import statement does not affect the file size of main.js. The code from library.js is loaded dynamically at runtime, and the size of the resulting bundle that gets loaded into the browser depends on the configuration of your build system.
So, to summarize, using the import statement allows you to include code from other modules in your code, making it available within the scope of the importing file, but it does not physically copy the code over, and it does not affect the file size of the importing file.