例子:使用Grunt创建一个Node.js类库

 

  1. 创建一个文件夹。
  2. 打开命令行或者powershell, 运行npm init,根据提示填入package的信息。
  3. 在文件夹中创建index.js文件。

/*!

* mymongolib

* Copyright(c) 2009-2013 Blabla

* MIT Licensed

*/

 

'use strict';

 

module.exports = require('./lib/mymongolib');

 

  1. 在文件夹中创建lib目录,然后在新目录中创建mymongolib.js文件。

'use strict'

 

function MyMonboLib(connStr)

{

this.ConnStr = connStr;

 

this.TestConn = function()

{

return true;

}

 

this.DeleteOneDoc(collName, _id)

{

return true;

}

 

}

 

module.exports = MyMongoLib;

 

  1. 回到项目的根目录文件夹,然后里面创建Gruntfile.js文件。

module.exports = function(grunt) {

 

// Project configuration.

grunt.initConfig({

pkg: grunt.file.readJSON('package.json'),

uglify: {

options: {

banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */ '

},

build: {

src: ['lib/<%= pkg.name %>.js'],

dest: 'dist/<%= pkg.name %>.js'

}

}

});

 

// Load the plugin that provides the "uglify" task.

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

 

// Default task(s).

grunt.registerTask('default', ['uglify']);

 

};

 

  1. 在命令行或者PowerShell中安装grunt.

npm install grunt --save-dev

 

  1. 在命令行或者PowerShell中安装grunt-contrib-uglify模块。

npm install grunt-contrib-uglify --save-dev

 

  1. 在命令行或者PowerShell中执行grunt命令。

grunt

 

结果如下:

Running "uglify:build" (uglify) task

>> 1 file created 265 B → 193 B

 

此时看到项目的根目录下,自动创建了一个dist文件夹,里面自动创建了一个mymongolib.js文件, 文件内容如下:

/*! mymongolib 2017-11-07 */

 

"use strict";function MyMonboLib(n){return this.ConnStr=n,this.TestConn=function(){return!0},this.DeleteOneDoc(collName,_id),!0}module.exports=MyMongoLib;

 

大功告成!

 

 

 

附录1:

当然,如果只想对一个js文件执行grunt操作,就不需要创建index.js和lib文件夹里面的文件,直接将文件放在根目录,然后将GruntFile.js文件中的路径改一下就好了。

 

附录2:

如何创建一个 示例 GruntFile.

  1. 安装grunt-cli

npm install -g grunt-cli

 

  1. 安装windows版本的git.
  2. 建立一个空文件夹。
  3. 从命令行或者PowerShell中定位到新文件夹,然后从github上下载模板。

git clone https://github.com/gruntjs/grunt-init-gruntfile.git ~/.grunt-init/gruntfile

 

  1. 创建 sample Docker file.

grunt-init gruntfile

 

这个命令会给出提示:

Please answer the following:

[?] Is the DOM involved in ANY way? (Y/n) n

[?] Will files be concatenated or minified? (Y/n) y

[?] Will you have a package.json file? (Y/n) y

[?] Do you need to make any changes to the above before continuing? (y/N) n

 

Writing Gruntfile.js...OK

Writing package.json...OK

 

Initialized from template "gruntfile".

 

这样,在文件夹中就有了对应的GruntFile.js和package.json文件,可以用来做样例或者从中复制粘贴一些代码用。

原文地址:https://www.cnblogs.com/time-is-life/p/7798325.html