I only came across this practice recently while looking at Apollo Client examples - I didn't realize all import statements could be at the bottom of a .js file. This seems like a great idea because it's rare that on opening a file the import statements are what I'm looking primarily to deal with.
In cases where order does not matter, is there any disadvantage we should be aware of with this practice?
This may be an example-only practice since the same company puts imports at the top in production code - but I'm not sure why it couldn't apply to production code. We're using TypeScript but I believe the concerns are the same with vanilla ES6.
Pure and Non Pure Modules A module with side-effects is one that changes the scope in other ways then returning something, and it's effects are not always predictable, and can be affected by outside forces (non pure function).
Import order does not matter. If a module relies on other modules, it needs to import them itself.
The curly braces are used only for import when export is named. If the export is default then curly braces are not used for import. Save this answer.
One of the major differences between require() and import() is that require() can be called from anywhere inside the program whereas import() cannot be called conditionally, it always runs at the beginning of the file. To use the require() statement, a module must be saved with . js extension as opposed to .
Normally, you'd want to declare/define something first, then use it. Using it first and then defining it seems weird. Someone reading your code would expect the imports to be at the top of the file.
This is also true for functions: you could use them before you declare them, but someone who reads the code would expect to find the declaration of the function a few lines above, not below:
var result = add(10, 5);
// some other code
function add (a, b) {
return a + b;
}
This seems like a great idea because it's rare that on opening a file the import statements are what I'm looking primarily to deal with.
I disagree. When I look at a file, I'm interested in its dependencies and its relation to other files in the project.
Let's say you want to understand what a certain file is about. Normally, you would glance through the code, first looking at the imports, then looking at the code that uses these imports. Otherwise, you would encounter a whole lot of things that you've never seen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With