how to minify js files in order via grunt-contrib-uglify?

后端 未结 9 2030
执念已碎
执念已碎 2021-02-01 14:51

I have a directory like below:

/folder/b.js
/folder/jQuery.js
/folder/a.js
/folder/sub/c.js

I want to minify all these js files in one js file

相关标签:
9条回答
  • 2021-02-01 15:29

    This can be done using the following Grunt tasks:

    1. https://github.com/gruntjs/grunt-contrib-concat concatenates files
    2. https://github.com/gruntjs/grunt-contrib-uglify minifies concatenated files

    EDIT

    I usually run all my files through a Grunt concatenation task using grunt-contrib-concat. Then I have another task to uglify the concatenated file using grunt-contrib-uglify.

    0 讨论(0)
  • 2021-02-01 15:29

    You're probably not going to like this, but the best way is to define your js source files as AMD modules and use Requirejs to manage the order in which they load. The grunt-contrib-requirejs task will recurse your dependency tree and concatenate the js files in the necessary order into one big js file. You will then use uglify (actually r.js has uglify built-in) to minify the big file.

    https://github.com/danheberden/yeoman-generator-requirejs has a good example gruntfile and template js files to work from.

    EDIT

    I've recently started using CommonJS modules instead of AMD since it's much closer to the ES6 module spec. You can achieve the same results (1 big complied+concatenated js file) by running commonjs modules through Browserify. There are plugins for both grunt and gulp to manage the task for you.

    EDIT

    I'd like to add that if your site is written using ES6 that Rollup is the best new concatenating package. In addition to bundling your files, it will also perform tree shaking, removing parts of libraries you use if included via an import statement. This reduces your codebase to just what you need without the bloat of code you'll never use.

    0 讨论(0)
  • 2021-02-01 15:30

    I ran into the same issue. A quick fix is just to change the filenames - I used 1.jquery.min.js, 2.bootstrap.min.js, etc.

    0 讨论(0)
提交回复
热议问题