如何使用 Grunt.js (0.3.x) 连接和缩小多个 CSS 和 JavaScript 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13713273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:43:03  来源:igfitidea点击:

How to concatenate and minify multiple CSS and JavaScript files with Grunt.js (0.3.x)

javascriptcssconcatenationminifygruntjs

提问by Jasdeep Khalsa

Note: This question is only relevant for Grunt 0.3.x and has been left for reference. For help with the latest Grunt 1.x release please see my comment below this question.

注意:此问题仅与 Grunt 0.3.x 相关,已留作参考。有关最新 Grunt 1.x 版本的帮助,请参阅我在此问题下方的评论。

I'm currently trying to use Grunt.js to setup an automatic build process for first concatenating and then minifying CSS and JavaScript files.

我目前正在尝试使用 Grunt.js 来设置一个自动构建过程,用于首先连接然后缩小 CSS 和 JavaScript 文件。

I have been able to successfully concatenate and minify my JavaScript files, although each time I run grunt it seems to just append to the file instead of overwriting them.

我已经能够成功地连接和缩小我的 JavaScript 文件,尽管每次我运行 grunt 它似乎只是附加到文件而不是覆盖它们。

As for the minifying or even concatenating CSS, I have been unable to do this as of yet!

至于缩小甚至连接 CSS,到目前为止我还无法做到这一点!

In terms of grunt CSS modules I have tried using consolidate-css, grunt-css& cssminbut to no avail. Could not get my head around how to use them!

就 grunt CSS 模块而言,我尝试使用consolidate-css, grunt-css&cssmin但无济于事。无法理解如何使用它们!

My directory structure is as follows (being a typical node.js application):

我的目录结构如下(是一个典型的 node.js 应用程序):

  • app.js
  • grunt.js
  • /public/index.html
  • /public/css/[various css files]
  • /public/js/[various javascript files]
  • 应用程序.js
  • grunt.js
  • /public/index.html
  • /public/css/[各种css文件]
  • /public/js/[各种javascript文件]

Here is what my grunt.js file currently looks like in the root folder of my application:

这是我的 grunt.js 文件当前在我的应用程序的根文件夹中的样子:

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: '<json:package.json>',
    concat: {
      dist: {
        src: 'public/js/*.js',
        dest: 'public/js/concat.js'
      }
    },
    min: {
      dist: {
        src: 'public/js/concat.js',
        dest: 'public/js/concat.min.js'
      }
    },
    jshint: {
      options: {
        curly: true,
        eqeqeq: true,
        immed: true,
        latedef: true,
        newcap: true,
        noarg: true,
        sub: true,
        undef: true,
        boss: true,
        eqnull: true,
        node: true
      },
      globals: {
        exports: true,
        module: false
      }
    },
    uglify: {}
  });

  // Default task.
  grunt.registerTask('default', 'concat min');

};

So just to summarise I need help with two questions:

所以总结一下我需要帮助解决两个问题:

  1. How to concatenate and minify all my css files under the folder /public/css/into one file, say main.min.css
  2. Why does grunt.js keep on appending to the concatenated and minified javascript files concat.jsand concat.min.jsunder /public/js/instead of overwriting them each time the command gruntis run?
  1. 如何将文件夹下的所有 css 文件连接并缩小/public/css/到一个文件中,例如main.min.css
  2. 为什么grunt.js不断追加到串联和精缩的JavaScript文件concat.js,并concat.min.js根据/public/js/,而不是每一个命令时覆盖它们grunt运行?


Updated 5th of July 2016 - Upgrading from Grunt 0.3.x to Grunt 0.4.x or 1.x

2016 年 7 月 5 日更新 - 从 Grunt 0.3.x 升级到 Grunt 0.4.x 或 1.x

Grunt.jshas moved to a new structure in Grunt 0.4.x(the file is now called Gruntfile.js). Please see my open source project Grunt.js Skeletonfor help with setting up a build process for Grunt 1.x.

Grunt.js已移至中的新结构Grunt 0.4.x(该文件现在称为Gruntfile.js)。请参阅我的开源项目Grunt.js Skeleton以获取有关为Grunt 1.x.

Moving from Grunt 0.4.xto Grunt 1.xshould not introduce many major changes.

Grunt 0.4.xGrunt 1.x不应该引入许多重大变化

回答by jaime

concat.js is being included in the concattask's source files public/js/*.js. You could have a task that removes concat.js(if the file exists) before concatenating again, pass an array to explicitly define which files you want to concatenate and their order, or change the structure of your project.

concat.js 被包含在concat任务的源文件中public/js/*.js。您可以concat.js在再次连接之前删除(如果文件存在)任务,传递数组以明确定义要连接的文件及其顺序,或更改项目的结构。

If doing the latter, you could put all your sources under ./srcand your built files under ./dest

如果执行后者,您可以将所有源代码放在下面,./src并将构建的文件放在下面./dest

src
├── css
│?? ├── 1.css
│?? ├── 2.css
│?? └── 3.css
└── js
    ├── 1.js
    ├── 2.js
    └── 3.js

Then set up your concattask

然后设置你的concat任务

concat: {
  js: {
    src: 'src/js/*.js',
    dest: 'dest/js/concat.js'
  },
  css: {
    src: 'src/css/*.css',
    dest: 'dest/css/concat.css'
  }
},

Your mintask

你的最小任务

min: {
  js: {
    src: 'dest/js/concat.js',
    dest: 'dest/js/concat.min.js'
  }
},

The build-in mintask uses UglifyJS, so you need a replacement. I found grunt-cssto be pretty good. After installing it, load it into your grunt file

内置的min任务使用 UglifyJS,因此您需要替换。我发现grunt-css非常好。安装后,将其加载到您的 grunt 文件中

grunt.loadNpmTasks('grunt-css');

And then set it up

然后设置一下

cssmin: {
  css:{
    src: 'dest/css/concat.css',
    dest: 'dest/css/concat.min.css'
  }
}

Notice that the usage is similar to the built-in min.

请注意,用法类似于内置的 min。

Change your defaulttask to

将您的default任务更改为

grunt.registerTask('default', 'concat min cssmin');

Now, running gruntwill produce the results you want.

现在,运行grunt将产生您想要的结果。

dest
├── css
│?? ├── concat.css
│?? └── concat.min.css
└── js
    ├── concat.js
    └── concat.min.js

回答by Augusto Altman Quaranta

I want to mention here a very, VERY, interesting technique that is being used in huge projects like jQuery and Modernizr for concatenate things.

我想在这里提到一个非常非常有趣的技术,它被用于像 jQuery 和 Modernizr 这样的大型项目来连接事物。

Both of this projects are entirely developed with requirejs modules (you can see that in their github repos) and then they use the requirejs optimizer as a very smart concatenator. The interesting thing is that, as you can see, nor jQuery neither Modernizr needs on requirejs to work, and this happen because they erase the requirejs syntatic ritual in order to get rid of requirejs in their code. So they end up with a standalone library that was developed with requirejs modules! Thanks to this they are able to perform cutsom builds of their libraries, among other advantages.

这两个项目都是完全用 requirejs 模块开发的(你可以在他们的 github 仓库中看到),然后他们使用 requirejs 优化器作为一个非常智能的连接器。有趣的是,正如您所看到的,无论是 jQuery 还是 Modernizr 都不需要在 requirejs 上工作,这是因为它们删除了 requirejs 语法规则,以便在代码中摆脱 requirejs。所以他们最终得到了一个用 requirejs 模块开发的独立库!多亏了这一点,他们能够执行库的 cutom 构建,以及其他优势。

For all those interested in concatenation with the requirejs optimizer, check out this post

对于所有对与 requirejs 优化器连接感兴趣的人,请查看这篇文章

Also there is a small tool that abstracts all the boilerplate of the process: AlbanilJS

还有一个小工具可以抽象出流程的所有样板:AlbanilJS

回答by Anshul

I agree with above answer. But here is another way of CSS compression.

我同意上面的回答。但这是另一种 CSS 压缩方式。

You can concat your CSS by using YUI compressor:

你可以使用YUI 压缩器来连接你的 CSS :

module.exports = function(grunt) {
  var exec = require('child_process').exec;
   grunt.registerTask('cssmin', function() {
    var cmd = 'java -jar -Xss2048k '
      + __dirname + '/../yuicompressor-2.4.7.jar --type css '
      + grunt.template.process('/css/style.css') + ' -o '
      + grunt.template.process('/css/style.min.css')
    exec(cmd, function(err, stdout, stderr) {
      if(err) throw err;
    });
  });
}; 

回答by Inc33

You don't need to add the concat package, you can do this via cssmin like this:

你不需要添加 concat 包,你可以通过 cssmin 这样做:

cssmin : {
      options: {
            keepSpecialComments: 0
      },
      minify : {
            expand : true,
            cwd : '/library/css',
            src : ['*.css', '!*.min.css'],
            dest : '/library/css',
            ext : '.min.css'
      },
      combine : {
        files: {
            '/library/css/app.combined.min.css': ['/library/css/main.min.css', '/library/css/font-awesome.min.css']
        }
      }
    }

And for js, use uglify like this:

对于 js,像这样使用 uglify:

uglify: {
      my_target: {
        files: {
            '/library/js/app.combined.min.js' : ['/app.js', '/controllers/*.js']
        }
      }
    }

回答by Donald

I think may be more automatic, grunt task usemin take care to do all this jobs for you, only need some configuration:

我认为可能更自动化,grunt 任务 usemin 会为您完成所有这些工作,只需要一些配置:

https://stackoverflow.com/a/33481683/1897196

https://stackoverflow.com/a/33481683/1897196