JavaScript dependency management

后端 未结 6 1910
清歌不尽
清歌不尽 2020-12-08 08:06

I am currently maintaining a large number of JS files and the dependency issue is growing over my head. Right now I have each function in a separate file and I manually main

6条回答
  •  独厮守ぢ
    2020-12-08 08:13

    As @bobince already suggested, doing static analysis on a JavaScript program is a close to impossible problem to crack. Google Closure compiler does it to some extent but then it also relies on external help from JSDoc comments.

    I had a similar problem of finding the order in which JS files should be concatenated in a previous project, and since there were loads of JS files, manually updating the inclusion order seemed too tedious. Instead, I stuck with certain conventions of what constitutes a dependency for my purposes, and based upon that and using simple regexp :) I was able to generated the correct inclusion order.

    The solution used a topological sort algorithm to generate a dependency graph which then listed the files in the order in which they should be included to satisfy all dependencies. Since each file was basically a pseudo-class using MooTools syntax, there were only 3 ways dependencies could be created for my situation.

    1. When a class Extended some other class.
    2. When a class Implemented some other class.
    3. When a class instantiated an object of some other class using the new keyword.

    It was a simple, and definitely a broken solution for general purpose usage but it served me well. If you're interested in the solution, you can see the code here - it's in Ruby.

    If your dependencies are more complex, then perhaps you could manually list the dependencies in each JS file itself using comments and some homegrown syntax such as:

    // requires: Array
    // requires: view/TabPanel
    // requires: view/TabBar
    

    Then read each JS file, parse out the requires comments, and construct a dependency graph which will give you the inclusion order you need.

提交回复
热议问题