Grunt-将多个文件最小化/处理为一个文件

Grunt - Minifying/processing multiples files into one

本文关键字:文件 一个 最小化 Grunt- 处理      更新时间:2023-09-26

我是Grunt的新手,我迷失在它的所有选项中。我试着做两件事:

  • 每次更改一个js文件时,都要将其最小化为一个
  • 当我的某个scs文件更改时,处理特定的scs文件

这是我目前得到的Gruntfile.js:

module.exports = function (grunt) {
    grunt.initConfig({
    // define source files and their destinations
    uglify: {
        files: { 
            src: 'js/*.js',  // source files mask
            dest: 'jsm/',    // destination folder
            expand: true,    // allow dynamic building
            flatten: true,   // remove all unnecessary nesting
            ext: '.min.js'   // replace .js to .min.js
        }
    },
    watch: {
        js:  { files: 'js/*.js', tasks: [ 'uglify' ] },
    }
});
// load plugins
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-uglify');
// register at least this one task
grunt.registerTask('default', [ 'uglify' ]);

};

我怎样才能做到这一点?

使用grunt contrib concat

grunt.initConfig({    
  concat: {
    dist: {
      src: ['files/**.min.js'],
      dest: 'project.js',
    },
  }
});

您应该将所有文件封装在一个匿名函数中,并使用var定义变量,这样就不会在文件之间发生变量冲突。

(function(){
  // foo has function scope
  var foo = 3; 
  console.log(foo);
  // FOO is a global variable and 
  // can be accessed between files
  window.FOO = 3;
  console.log(FOO);
}).call()