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

后端 未结 9 2027
执念已碎
执念已碎 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

    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.

提交回复
热议问题