Concat and minify JS files in Node

前端 未结 9 1700
遥遥无期
遥遥无期 2020-12-04 09:40

Is there any module in NodeJS to concatenate and minify JavaScript files?

9条回答
  •  清歌不尽
    2020-12-04 09:53

    Try these two plugins for Grunt

    https://www.npmjs.org/package/grunt-contrib-concat

    https://www.npmjs.org/package/grunt-contrib-uglify

    You can install everything you need like so:

    npm install grunt
    npm install grunt-cli
    npm install grunt-contrib-concat
    npm install grunt-contrib-uglify
    

    Then create your grunt file, like so:

    Gruntfile.js

    module.exports = function(grunt){
      grunt.initConfig({
        concat: {
          options: {
            process: function(src, path){
              return '\n/* Source: ' + path + ' */\n' + src;
            }
          },
          src: [
            '../src/**/*.js'
          ],
          dest: '../bin/app-debug.js'
        },
        uglify: {
          src: '../bin/app-debug.js',
          dest: '../bin/app.js'
        },
        watch: {
          options: {
            atBegin: true,
            event: ['all']
          },
          src: {
            files: '../src/**/*.js',
            tasks: ['concat']
          },
          dist: {
            files: '../bin/app-debug.js',
            tasks: ['uglify']
          },
        }
      }
    
      grunt.loadNpmTasks('grunt-contrib-concat');
      grunt.loadNpmTasks('grunt-contrib-uglify');
    
      grunt.registerTask('default', ['watch']);
    }
    

    Finally, type grunt in the terminal and Grunt will start watching your JavaScript files for changes and automatically concat and uglify them (whenever you save a change to your js files in ../src/

提交回复
热议问题