问题
I need to use the Google Closure compiler.jar to minify a huge project I am working on. I have multiple js files that I want to compile into a single game.min.js file. I know I can use the following:
java -jar compiler.jar --js file1.js --js file2.js --js etc, etc --js_output_file game.min.js
...but I have a LOT of files and as I understand it Closure doesn't have support for adding a directory and finding all the *.js files residing under that directory. My fumbling google searches are not giving me any tools that I can use for the job (or nothing that works at any rate).
Has anyone out there found / used / written a script that loops through a directory and spits out all the .js files into a single minified file? I am hopeless with php, python, etc, so any help greatly appreciated.
回答1:
You can use ant to automate the use of the closure compiler.
I do it in two separate steps, concatenation then compilation :
<concat destfile="src/somepath/app.concat.js">
<filelist dir="src/somepath">
<file name="a.js" />
<file name="b.js" />
<file name="c.js" />
<file name="d.js" />
</filelist>
</concat>
<jscomp compilationLevel="simple" warning="quiet" debug="false" output="src/app.min.js">
<sources dir="src/somepath">
<file name="app.concat.js" />
</sources>
</jscomp>
Be careful that the order of the files is important. That's why you can't simply pass a fileset to the jscomp
task.
回答2:
You can also use wildcards when specifying files. You could change your example to:
java -jar compiler.jar --js *.js --js_output_file game.min.js
This should combine all of the .js files in your current working directory into the output file you've specified.
回答3:
You should concatenate all your source files before you apply Google Closure compiler.
For all related tasks you could use Ant build tool. Also, there is a great Grunt.js project, which is more convenient for JS. There are grunt-contrib-concat
and grunt-shell
npm modules for Grunt.js, the first is for concatenation, the other is for running console commands.
Your Gruntfile.js could look like this:
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
concat: {
js: {
src: ['src/js/*.js'],
dest: 'dist/pre-build.js'
}
},
shell: {
optimize: {
command: 'google closure compiler command here',
stdout: true
}
}
});
grunt.loadNpmTasks('grunt-shell');
grunt.loadNpmTasks('grunt-contrib-concat');
// Default task.
grunt.registerTask('default', ['concat', 'shell:optimize']);
};
来源:https://stackoverflow.com/questions/15271317/creating-a-script-to-use-google-closure-for-multiple-javascript-files