Build process for compiling client JS modules into one script
Your approach is sound. The optimizer of RequireJS called r.js also scans the code for calls to methods with a special name (define and require) to detect dependencies.

You can see how this detection works in the file transform.js. As you can see, this optimizer uses a JavaScript parser, which is more reliable than using regular expressions: for example, your regular expression may match a call in a comment, which would be skipped using a parser.

There is another way to declare dependencies for RequireJS though, which is described in the Asynchronous Module Definition specification: wrap each module in a call to a function and list the dependencies explicitly in an array.

You may also be interested in the use of a simpler pattern for the declaration of modules, independently of the loader used.

With regards to circular dependencies ("when two files require each other"), there are two ways to handle them:


detect them and fail, forcing the developer to avoid them in their code
load one of the two modules with only parts of their dependencies, which requires extra care from developers: they can no longer be sure that all dependencies are available when the module runs, and must check before calling methods and accessing properties on required objects 


Both approaches have drawbacks.