This question has already been answered:

Hello. I am writing code that is quite huge. Maybe I'm doing something wrong, but as long as everything works and suits me)) The problem is that the more the code, the less it is clear and readable. I would like to split it into several .js files and connect using import. Is it possible? If so, please explain how to do it. Worked only with js and jquery . I don't have much JS skills. So I ask you to state everything in order, if not difficult.

Reported as a duplicate at Grundy. javascript Jan 13 '17 at 15:51 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • And you can code ???? - L. Vadim
  • one
    It is possible but not necessary, my code will not help anything, of course you can tell me how to reduce it and optimize it more, but right now I’m concerned about a specific question, let's not respond :) - elik

3 answers 3

Good day! To organize the modular structure of js, you can use requireJs , then connecting modules will look like this:

 define([ "jquery" ], function($){ // use jquery } 

For a more pleasant import / export, you can use the features of the js standard es6. Here you can not do without any collector who will translate es6 to es5 standard. For example, you can use gulp, webpack, grunt, or any other babel, es6fy, browserfy, etc., then the code will look even nicer:

 import {$} from "../vendor/jquery"; 
  • Thank you very much, yes, this is what I’m looking for) and what can you advise from the collectors? I read a hundred modules about the webpack, but I don’t know much. And if this does not greatly affect the productivity of the script? - elik
  • They have their advantages. Webpack, for example, can do livereload, and gulp, in my opinion, is simpler and clearer. You can try gulp + babel. Here I made a small template for myself for such projects frontend_gulp_template - Mikl
  • one
    In addition to requireJs, there is also SystemJS - Pavel Mayorov

If you are using jQuery, you can connect the file using jQuery.getScript () :

 $.getScript("imported_script.js", function(){ alert("Скрипт загружен!"); }); 
  • and using this method, you can access the variable functions of the loaded file ("script")? - elik

Good day. Check out libraries such as requireJS. About the connection written above. Also, you can write in TypeScript and use standard ES6 modules through its import and export. Study design patterns, such as: module, observer, mediator, facade. This will help you structure your code and write more literate web applications.

  • Good afternoon! Thank you very much for your advice for the future. I will be gratefully interested in such details. Thank you for your humanity! - elik