JS modules: import JS code | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

JS modules: import JS code

I recently found modules while recapping the ES6 lessons. Because I'm working on a JS project with already 1000+ lines I thought it might be useful to split the source code into multiple files to increase the maintainability. But when I looked JS modules up for more information I got a little confused because there seem to be at least three different possible ways to implement them: import/export, Components.utils.import() and AMD/CommonJS. Now I have following questions: 1. Can I simply include JS code (as library) into a JS file (without using a separate script tag). Or in other words, I just want to have one script tag that uses multiple files. 2. Which of the available solutions is the best way to do this (if possible) ?

12th Mar 2019, 7:49 PM
Aaron Eberhardt
Aaron Eberhardt - avatar
4 Answers
+ 6
Aaron Eberhardt It sounds like you're evolving your Javascript skills as you are at a place where you can think about organizing your code beyond a single file. The simple answer is to use ES6 import / export for module loading at this point. In the past, CommonJS was used for NodeJS and AMD via RequireJS in the browser. ES6 supports both synchronous (CommonJS) and asynchronous (AMD) module loading.
13th Mar 2019, 6:18 AM
David Carroll
David Carroll - avatar
+ 10
AMD – one of the most ancient module systems, initially implemented by the library require.js. CommonJS – the module system created for Node.JS server. UMD – one more module system, suggested as a universal one, compatible with AMD and CommonJS. Now all these slowly become a part of history, but we still can find them in old scripts. The language-level module system appeared in the standard in 2015, gradually evolved since then, and is now supported by all major browsers and in Node.js.
13th Mar 2019, 6:21 AM
Вап
+ 2
If you do not like to use es import export feature, you could form your own closure and release and export an object literal.
13th Mar 2019, 4:30 AM
Calviղ
Calviղ - avatar
+ 1
Thank you Calviղ, David Carroll and 4rontender for your helpful answers!
13th Mar 2019, 8:55 AM
Aaron Eberhardt
Aaron Eberhardt - avatar