user2122223
user2122223

Reputation: 149

Organize and merge JS files, Google Closure?

I'm trying to merge all my plugins so I can change from this:

<html>
    <head>
    </head>
    <body>    
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script src="js/plugin1.js"></script>
        <script src="js/plugin2.js"></script>
        <script src="js/plugin3.js"></script>
        <script src="js/plugin4.js"></script>
    </body>
</html>

to this:

<html>
    <head>
    </head>
    <body>    
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script src="js/plugins.min.js"></script>
    </body>
</html>

The main idea is to have a tool to "auto import" into my plugins.js file all the plugins I need for my websites and also minify them when compiling. I've been testing with Google Closure (downloadable Java version of the compiler) and I figured how to minify files but I can't import external files. So I'd like to ask you if you could maybe tell me if Google Closure is the tool I'm looking for or if I should use another tool or method.

With "auto import" I mean something like:

PLUGINS/HELLO.JS

function hello(name) {
    alert('Hello, ' + name);
}

PLUGINS.JS

@import hello.js
hello('New user');

I hope I made myself clear, I apologize if I messed up with my English.

Thanks!!

Upvotes: 5

Views: 3924

Answers (4)

0gog0
0gog0

Reputation: 159

I asked myself same question, and found no acceptable answer. Only way to join many files is putting multiple "--js" params in command line:

java -jar compiler.jar --js 1.js --js 2.js --js 3.js --js_output_file all.js

I tried put lines like this (which used in Closure Compiler service UI):

// ==ClosureCompiler==
// @code_url 1.js
// @code_url 2.js
// @code_url 3.js
// ==/ClosureCompiler==

... in "main.js" and compile it - no effect. :(

Upvotes: 5

Chad Killingsworth
Chad Killingsworth

Reputation: 14411

Closure-compiler can do exactly what you want, but only with Closure-library code because of it's use of goog.require calls. With jQuery code, the best it could do is compile ALL of your plugins together into a single file, but it wouldn't take into account actual usage.

Unfortunately, I don't know of anything that will do this for code in general.

Note: This isn't expected to be the accepted answer for the question. The question asked specifically about Closure-compiler and I wanted to make sure at least somewhere it was stated that the compiler isn't going to work as desired.

Upvotes: 1

EsTeGe
EsTeGe

Reputation: 3055

Use RequireJs with its optimization possibilities. Have a look here: http://requirejs.org/docs/optimization.html

Upvotes: 2

kevmc
kevmc

Reputation: 1294

You might want to take a look at require.js

Upvotes: 0

Related Questions