+ 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) ?
4 Respostas
+ 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.
+ 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.
+ 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.
+ 1