例子:使用Grunt建立一個Node.js類庫

 

  1. 建立一個文件夾。
  2. 打開命令行或者powershell, 運行npm init,根據提示填入package的信息。
  3. 在文件夾中建立index.js文件。

/*! git

* mymongolib github

* Copyright(c) 2009-2013 Blabla shell

* MIT Licensed npm

*/ json

 

'use strict'; windows

 

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

 

  1. 在文件夾中建立lib目錄,而後在新目錄中建立mymongolib.js文件。

'use strict' grunt

 

function MyMonboLib(connStr) ui

{ this

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") %> */\n'

},

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文件,能夠用來作樣例或者從中複製粘貼一些代碼用。

相關文章
相關標籤/搜索