【问题标题】:How to set the environment for Grunt?如何为 Grunt 设置环境?
【发布时间】:2015-06-06 03:20:13
【问题描述】:

我为developmentproduction 两个环境定义了Gruntfile.js 的任务部分。但我不明白,Grunt 是如何决定的,是否使用哪个环境部分。

Gruntfile.js

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    less: {
      development: {
        options: {
          paths: ["public/css"]
        },
        files: {
          "public/css/style.css": "public/css/style.less"
        }
      },
      production: {
        options: {
          paths: ["public/css"],
          plugins: [
          ],
          modifyVars: {
          }
        },
        files: {
          "public/css/style.css": "public/css/style.less"
        }
      }
    },
    watch: {
      css: {
        files: 'public/css/*.less',
        tasks: ['less'],
        options: {
          livereload: true,
        },
      },
    }
  });

  // Load the plugin that provides the "less" task.
  grunt.loadNpmTasks('grunt-contrib-less');
  // Load the plugin that provides the "watch" task.
  grunt.loadNpmTasks('grunt-contrib-watch');

  // Default task(s).
  grunt.registerTask('default', ['less', 'watch']);

};

如何让 Grunt 知道当前处于活动状态的环境?

【问题讨论】:

    标签: gruntjs config development-environment production-environment gruntfile


    【解决方案1】:

    作为替代,我建议您创建一个development 任务并使用grunt development 运行它

    // Default task(s).
    grunt.registerTask('default', ['less:production', 'watch']);
    
    // Development task
    grunt.registerTask('development', ['less:development', 'watch']);
    

    【讨论】:

    • 感谢您的回答!有用。是否也可以从单独的文件中获取环境信息?我的想法是将此信息保存在非版本化文件中,这样就不必每次都考虑我当前在哪个环境中执行命令。
    • 在 LESS 的情况下(但也许每个模块都有可能,我没有测试它)调用 grunt less:development 也可以。如果您知道它是否适用于每项任务,请随时使用此信息扩展您的答案。
    • 嗨@automatix,这有点超出问题范围。我建议您使用这些信息创建另一个问题,我想其他人也可能会觉得它有用。 :)
    【解决方案2】:

    您可以拥有两个不同的 grunt 文件,一个用于开发环境,一个用于生产环境(例如 gruntfile.dev.jsgruntfile.prod.js),并通过在 npm grunt 命令中指定文件名来指定应将哪个文件视为对应的 grunfile像这样

    grunt --gruntfile gruntfile.prod.js
    

    请记住,您可以为 dev 和 prod grunt 命令定义两个别名 见下文

    "scripts": 
     {
        "build:prod": "grunt --gruntfile gruntfile.prod.js",
        "build:dev": "grunt --gruntfile gruntfile.dev.js",
     }
    

    因此,输入 npm run build:prod 将运行 prod gruntfile,输入 npm run build:dev 将运行 dev gruntfile。

    通过这样做,您拥有更大的灵活性,并且更容易维护与您的 grunt 配置相关的更改

    【讨论】:

      猜你喜欢
      • 2018-01-04
      • 2020-02-14
      • 2023-02-18
      • 2014-07-15
      • 2013-08-30
      • 2017-05-25
      • 2017-07-01
      • 1970-01-01
      • 2011-02-13
      相关资源
      最近更新 更多