zoukankan      html  css  js  c++  java
  • 使用Grunt构建任务管理脚本(转)

    Grunt是构建Web开发的一个系统,但它创建比较困难。在这个指南中,你将学会如何配置Grunt创建一个现代的Web项目。当你完成教程中的配置之后,你的Gruntfile将具有:

    • 从源目录中向目标目录复制文件;
    • 删除构建文件;
    • 编译Stylus文件和给他们添加前缀;
    • 编译CoffeeScript
    • 压缩CSSJavaScript文件;
    • 编译Jade
    • 当文件修改后自动构建源文件;
    • 运行开发者服务器

    Grunt具有一个中文版本官网,如果你对Grunt感兴趣,可以点击这里查阅相关中文文档。

    开始

    如果你还没有开始使用Grunt,你需要先安装“Node.js”和“NPM”。你还需要通过在命令端中输入命令npm install -g grunt-cli来安装Grunt。这样在你的系统中允许你在任何地方使用grunt命令使用你的Grunt。

    创建一个package.json文件,并添加下面的内容:

    {
      "name": "grunt_tutorial",
      "description": "An example of how to set up Grunt for web development.",
      "author": "Landon Schropp (http://landonschropp.com)",
      "dependencies": {
        "grunt": "0.x.x",
        "grunt-autoprefixer": "0.2.x",
        "grunt-contrib-clean": "0.5.x",
        "grunt-contrib-coffee": "0.7.x",
        "grunt-contrib-connect": "0.4.x",
        "grunt-contrib-copy": "0.4.x",
        "grunt-contrib-cssmin": "0.6.x",
        "grunt-contrib-jade": "0.8.x",
        "grunt-contrib-jshint": "0.6.x",
        "grunt-contrib-stylus": "0.8.x",
        "grunt-contrib-uglify": "0.2.x",
        "grunt-contrib-watch": "0.5.x"
      },
      "engine": "node >= 0.10"
    }

    这个文件定义了您的项目作为一个NPM包和您的项目所依赖需要的声明。每个声明都有自己的一个版本号。例如,grunt-contrib-copy:"0.4.x"告诉NPM安装0.4最新的版本grunt-contrib-copy包。在你的命令终端运行npm安装你需要管理插件。

    复制

    一个好的运行脚本总是能让源码和文件分开。这样分离允许你修改源文件而不会影响脚本。

    开始,你会让Grunt从source目录中复制文件到build目录中。需要创建一个Gruntfile.js文件,并将下面的代码复制到这个文件中:

    module.exports = function(grunt) {
      // 配置任务
      grunt.initConfig({
        copy: {
          build: {
            cwd: 'source',
            src: [ '**' ],
            dest: 'build',
            expand: true
          },
        },
      });
      // 加载任务
      grunt.loadNpmTasks('grunt-contrib-copy');
      // 定义任务
    };

    让我们来分解一下。在Node中,需要一个模块,通过modules.exports函数来调取并返回值。在Gruntfile文件中通过modules.exports告诉Node定义Grunt配置,并返回一个函数。grunt.initConfig是一个方法,他接受一个参数:一个对象的属性配置一个Grunt任务。

    在Grunt配置中,您已添加了一个copy任务。这个任务有一个子任务,叫build。在Grunt中,多个任务称为多任务。对于copy任务,你不需要此功能,但它仍然需要有至少一个子任务。

    在Grunt创建子任务是文件数组格式。这种格式是Grunt提供源文件到一个任务的一个格式方法之一。cwd指向源文件的目录都是相对的,和src指定源文件类似。**是一个通配符,用来匹配Grunt任何文件。dest是Grunt用来输出结果任务。你将设置build目录,告诉Grunt将内容复制到build目录中。如果有一个source/index.html文件,这个配置将输出build/index.html文件。最后,你设置expand参籹为true来开启这些选项。

    grunt.loadNpmTasks("grunt-contrib-copy")告诉Grunt从grunt-contrib-copy包中加载任务。这给我们一个copy命令,您可以在你的命令控制台中通过grunt copy命令实现复制功能。

    Clean

    现在你有一个build目录,他是用来完成clean任务。然后你将下面的配置复制到里面:

    clean: {
      build: {
        src: [ 'build' ]
      },
    },

    就像copy,你设置了一个clean目标和任务配置,clean配置了一个src,设置了build,用来移除build目录。

    接下来使用grunt.loadNpmTask("grunt-contrib-clean"),加载一个clean任务,允许你在命令终端运行grunt clean命令。

    grunt.loadNpmTasks('grunt-contrib-clean');
    

    Build

    如果你有一个build任务,在复制新的源文件之前需要先删除旧的build,这并不是很好,让我们来添加一个任务。

    // 定义任务
    grunt.registerTask(
      'build', 
      'Compiles all of the assets and copies the files to the build directory.', 
      [ 'clean', 'copy' ]
    );

    这个registerTask方法创建了一个新的任务。第一参数,build,定义了这个任务的名称。第二个用来描述这个任务。最后一个参数是一个将要运行的任务数组,这个build任务,先运行clean任务,接着运行copy任务。

    Stylus

    Stylus是一种CSS预处理语言。它在CSS上增强了几个功能,包括添加变量、嵌套和函数等功能。

    stylus: {
      build: {
        options: {
          linenos: true,
          compress: false
        },
        files: [{
          expand: true,
          cwd: 'source',
          src: [ '**/*.styl' ],
          dest: 'build',
          ext: '.css'
        }]
      }
    },

    这个任务与其他的任务稍有不同。这仍然是build的一子任务,但他包含两个属性:optionsfilesoptions指定了想要完成任务的行为。我们添加了两个选择项:compress决定CSS输出是否被压缩和linenos在Stylus源文件中选择器添加行号。

    files在格式化文件之前设置了一些数组参数。运行这个任务后,source目录下的.styl文件扩展编译输出文件.css

    现在stylus任务是将CSS文件输出到build目录,没有任何理由将Stylus文件复制到build目录任何地方。让我们修改copy配置来阻止这样的事情发生。

    copy: {
      build: {
        cwd: 'source',
        src: [ '**', '!**/*.styl' ],
        dest: 'build',
        expand: true
      },
    },
    

    在文件路径的开始处可以防止Grunt的匹配模式。别忘了在build任务中添加stylus

    grunt.registerTask(
      'build', 
      'Compiles all of the assets and copies the files to the build directory.', 
      [ 'clean', 'copy', 'stylus' ]
    );
    

    Autoprefixer

    Autoprefixer是Stylus尤物移人编译成CSS后,给CSS3属性添加前缀插件。他是一个强大的库,正如NibCompass

    继续添加autoprefixer配置:

    autoprefixer: {
      build: {
        expand: true,
        cwd: 'build',
        src: [ '**/*.css' ],
        dest: 'build'
      }
    },
    

    注意到模式了吗?这个配置非常类似于其他任务。一个明显的差异是cwddest两个都设置为build。使用的autoprefixer输出的文件和读取的文件在同一个目录中。

    和前面的一样,你也需要加载autoprefixer任务。

    grunt.loadNpmTask('grunt-autoprefixer');
    

    不是把所有的CSS任务添加到build中,创建一个添加样式的新任务和将任务添加到build中。

    // 配置任务
    grunt.registerTask(
      'stylesheets', 
      'Compiles the stylesheets.', 
      [ 'stylus', 'autoprefixer' ]
    );
    
    grunt.registerTask(
      'build', 
      'Compiles all of the assets and copies the files to the build directory.', 
      [ 'clean', 'copy', 'stylesheets' ]
    );
    

    CSS压缩

    客户端加载一群庞大的CSS文件文件,会真正的减慢网站加载时间。幸运的是grunt-contrib-cssmin包可以将CSS文件压缩,并将多个文件合并成一个单一的文件。我们再次开始配置。

    cssmin: {
      build: {
        files: {
          'build/application.css': [ 'build/**/*.css' ]
        }
      }
    },
    

    使用文件数组格式,这个配置使用Grunt的文件对象格式,将几个文件指定到一个目的地。所有build目录下的CSS文件压缩后输出到build/application.css

    加载CSS压缩任务包并且将stylesheets添加到任务中。

    grunt.loadNpmTasks('grunt-contrib-cssmin');
    
    grunt.registerTask(
      'stylesheets', 
      'Compiles the stylesheets.', 
      [ 'stylus', 'autoprefixer', 'cssmin' ]
    );
    

    CoffeeScript

    CoffeeScript是编译JavaScript一种奇特的语言。他有干净、漂亮的语法,包括类名和隐藏大量JavaScript不足的一面。

    将CoffeeScript加入到项目中非常容易。首先,添加到配置中:

    coffee: {
      build: {
        expand: true,
        cwd: 'source',
        src: [ '**/*.coffee' ],
        dest: 'build',
        ext: '.js'
      }
    },
    

    将源文件中的CoffeeScript文件,改变他们的扩展名为.js,并将他们输出到build目录中。接下来,通过grunt-contrib-coffee加载任务包。

    grunt.loadNpmTasks('grunt-contrib-coffee');
    

    scripts任务加载到build任务中:

    grunt.registerTask(
      'scripts', 
      'Compiles the JavaScript files.', 
      [ 'coffee' ]
    );
    
    grunt.registerTask(
      'build', 
      'Compiles all of the assets and copies the files to the build directory.', 
      [ 'clean', 'copy', 'stylesheets', 'scripts' ]
    );
    

    再次,你需要添加一个copy扩展,因为CoffeeScript文件并没有复制到build目录中。

    copy: {
      build: {
        cwd: 'source',
        src: [ '**', '!**/*.styl', '!**/*.coffee' ],
        dest: 'build',
        expand: true
      },
    },
    

    Uglify

    cssmin一样,Uglify压缩JavaScript文件,并将压缩成一个文件。这里是他的配置:

    uglify: {
      build: {
        options: {
          mangle: false
        },
        files: {
          'build/application.js': [ 'build/**/*.js' ]
        }
      }
    },
    

    默认情况之下,UglifyJS将使你的脚本用更短的名字来取代变量和函数名。如果你的项目代码是自已的那还是很方便的,如果要共享到另一个项目中,会带来问题。设置false将会关掉这种行为。

    cssmin任务一样,这个任务也需要添加文件对象格式。

    加载任务包,并像scripts任务将uglify添加到任务中:

    grunt.loadNpmTasks('grunt-contrib-uglify');
    
    grunt.registerTask(
      'scripts', 
      'Compiles the JavaScript files.', 
      [ 'coffee', 'uglify' ]
    );
    

    清理

    当你运行grunt build,除了build/application.cssbuild/application.js之外,其他所有的CSS和JavaScript文件都会挂在build目录下。既然你不需要他们,可以添加子任务删除它们,下面的是clean配置:

    clean: {
      build: {
        src: [ 'build' ]
      },
      stylesheets: {
        src: [ 'build/**/*.css', '!build/application.css' ]
      },
      scripts: {
        src: [ 'build/**/*.js', '!build/application.js' ]
      },
    },
    

    当你运行这个任务,哪果你没有指定子任务,Grunt会运行这些任务。如果你运行grunt clean,将执行clean:buildclean:stylesheetsclean:scripts。如果clean不能删除一个文件,它只是会忽略它,这个并不是什么问题。

    注意build/application.cssbuild/application.js排除了stylesheetsscripts的子任务。你并不想删除他们,这些毕竟是努力工作得来的。

    更新任务时,使用适应的子任务:

    // define the tasks
    grunt.registerTask(
      'stylesheets', 
      'Compiles the stylesheets.', 
      [ 'stylus', 'autoprefixer', 'cssmin', 'clean:stylesheets' ]
    );
    
    grunt.registerTask(
      'scripts', 
      'Compiles the JavaScript files.', 
      [ 'coffee', 'uglify', 'clean:scripts' ]
    );
    
    grunt.registerTask(
      'build', 
      'Compiles all of the assets and copies the files to the build directory.', 
      [ 'clean:build', 'copy', 'stylesheets', 'scripts' ]
    );
    

    Jade

    Jade是HTML模板语言。通过grunt-contrib-jade包将Jade添加到你的项目中:

    jade: {
      compile: {
        options: {
          data: {}
        },
        files: [{
          expand: true,
          cwd: 'source',
          src: [ '**/*.jade' ],
          dest: 'build',
          ext: '.html'
        }]
      }
    },
    

    styluscoffee任务一样,jade配置也使用了文件数组。在options内设置了data对象。当Jade文件编译时,这个对象传递到每个模板中。这非常方便,例如创建单独的开发或动态生成内容。

    和前面的一样,你需要在copy添加扩展:

    copy: {
      build: {
        cwd: 'source',
        src: [ '**', '!**/*.styl', '!**/*.coffee', '!**/*.jade' ],
        dest: 'build',
        expand: true
      },
    },
    

    别忘了在build中添加grunt-contrib-jade任务:

    grunt.loadNpmTasks('grunt-contrib-jade');
    
    grunt.registerTask(
      'build', 
      'Compiles all of the assets and copies the files to the build directory.', 
      [ 'clean:build', 'copy', 'stylesheets', 'scripts', 'jade' ]
    );
    

    Watch

    你的Gruntfile现在已经很强大了,但不是很好,因为你每次都得去运行grunt build。使用grunt-contrib-watch,就不需要每次运行。让我们来配置一个这样的任务,你会看到源代码,并自动构建他们的变化。

    watch: {
      stylesheets: {
        files: 'source/**/*.styl',
        tasks: [ 'stylesheets' ]
      },
      scripts: {
        files: 'source/**/*.coffee',
        tasks: [ 'scripts' ]
      },
      jade: {
        files: 'source/**/*.jade',
        tasks: [ 'jade' ]
      },
      copy: {
        files: [ 'source/**', '!source/**/*.styl', '!source/**/*.coffee', '!source/**/*.jade' ],
        tasks: [ 'copy' ]
      }
    },
    

    stylesheetsscriptsjade子任务可以监测到Stylus,CoffeeScript和Jade文件变化和运行各自的任务。在copy任务中测试所有剩下文件并将其复制到build目录下。

    再次,你需要加载Grunt任务。

    grunt.loadNpmTasks('grunt-contrib-watch');
    

    开发者服务器

    没有Web服务器开发环境是一个不完整的。grunt-contrib-connect包是一个全功能的静态文件服务器,用于你的项目中非常的完美。

    connect: {
      server: {
        options: {
          port: 4000,
          base: 'build',
          hostname: '*'
        }
      }
    },
    

    你配置的主机服务器build目录在4000端口上。默认情况之下,在你本地主机上连接服务器是localhost。你可以设置hostname*可以从任何地方访问服务器。

    和前面的一样,你需要给NPM任务中添加载加任务项。

    grunt.loadNpmTasks('grunt-contrib-connect');
    

    如果你在命令终端尝试运行grunt connect,服务器运行,然后马上停止。这是因为默认情况下,Grunt connet任务不会一直运行下去,你需要了解如何修改这个问题。

    默认

    在所有任务之中运行单个任务,并不很完美。default任务是这样设置:

    grunt.registerTask(
      'default', 
      'Watches the project for changes, automatically builds them and runs a server.', 
      [ 'build', 'connect', 'watch' ]
    );
    

    default任务运行build创建一个初始的build,然后它开始连接服务器,最后它会运行watch,监测文件变化和重新构建。因为watch一直在运行,所以服务器一直在运行。在你的控制台上运行grunt,然后到http://localhost:4000查看你的项目。

    总结

    在这篇教程中我们已经讨论了很多,但Grunt还有很多事情可以做。对于一个完整的Grunt列表插件,可以查看Grunt插件网站

    扩展阅读

    译者手语:整个翻译依照原文线路进行,并在翻译过程略加了个人对技术的理解。如果翻译有不对之处,还烦请同行朋友指点。谢谢!

    英文原文:http://www.sitepoint.com/writing-awesome-build-script-grunt/

    中文译文:http://www.w3cplus.com/tools/writing-awesome-build-script-grunt.html

  • 相关阅读:
    我爱java系列之---【微服务间的认证—Feign拦截器】
    我爱java系列之---【设置权限的三种解决方案】
    581. Shortest Unsorted Continuous Subarray
    129. Sum Root to Leaf Numbers
    513. Find Bottom Left Tree Value
    515. Find Largest Value in Each Tree Row
    155. Min Stack max stack Maxpop O(1) 操作
    painting house
    Minimum Adjustment Cost
    k Sum
  • 原文地址:https://www.cnblogs.com/JoannaQ/p/3360454.html
Copyright © 2011-2022 走看看