How to organize JavaScript code in a project for maintenance?

I am primarily a PHP developer, but lately I have been playing with a lot of JavaScript, mainly in jQuery.

The problem is that the code is getting harder to debug, and this is complicated because I listened to event listeners via HTML.

The code handles AJAX and DOM manipulation calls.

+6
source share
2 answers

Separation of problems

This means that you have three types of files: HTML, CSS, and JS.

You do not mix HTML, CSS or JS. Each of them is in its own file.

By simply keeping everything separate and never using inline javascript or inline CSS, you can solve most problems with organizing your code.

Another method is packers and minifiers.

My choice packages browserify (js) and less (css)

Packers mean that you have all your code in many files / modules, separated by a good design. Then, since sending many small files is expensive, you use the build time linker to turn all your js into one js file and all your css into one css file.

As for JS itself, I tend to go further and use the module loader. Browserify is both a packer and a module loader.

Modular loaders mean that you define small modules and load / require them when you need and where you need to.

I also implement an event-driven architecture and a mediator template to support my code very weakly. You can go further and implement something like a blackboard , but I have not tried it personally.

+5
source

You can use CommonJS "require" to split javascript code in many files, then use browserify or Webpack . Another option is Cor , which is a language that compiles into javascript focused on organization, cleanliness, and development experience.

0
source

Source: https://habr.com/ru/post/897993/


All Articles