• Posts tagged "bower"

Blog Archives

快速搭建Web环境 Angularjs + Express3 + Bootstrap3

AngularJS体验式编程系列文章,将介绍如何用angularjs构建一个强大的web前端系统。angularjs是由Google团队开发的一款非常优秀web前端框架。在当前如此多的web框架下,angularjs能脱颖而出,从架构设计上就高人一等,双向数据绑定,依赖注入,指令,MVC,模板。Angular.js创新地把后台技术融入前端开发,扫去jQuery一度的光芒。用angularjs就像写后台代码,更规范,更结构化,更可控。

关于作者

  • 张丹(Conan), 程序员Java,R,PHP,Javascript
  • weibo:@Conan_Z
  • blog: http://blog.fens.me
  • email: bsspirit@gmail.com

转载请注明出处:
http://blog.fens.me/angularjs-express3-bootstrap3/

angular-basic

前言

Angularjs越用越顺手,不仅代码量比jQuery少很多,而且实现思路特别清晰,构建大型的Web前端项目,真是最适合不过了。

Bootstrap让界面美观大方,就连像我这种不懂UE的人,也能做出专业级的水准。再结合Nodejs的Express做后端,三剑合并,太无敌了,大有统一前端开发的趋势,前途不可估量!

目录

  1. 从零开始手工创建Express3项目
  2. 新建Angularjs目录及文件
  3. 配置bower
  4. 配置Angularjs项目
  5. 增加Bootstrap
  6. 完整的项目

1. 从零开始手工创建Express3项目

系统环境:

  • Win7 64bit 旗舰版
  • node v0.10.5
  • npm 1.2.19
  • bower 1.1.2

本文截图中使用的开发工具是WebStorm,请参考文章:AngularJS最理想开发工具WebStorm

创建express项目


~ D:\workspace\javascript>express -e angular-basic
~ D:\workspace\javascript>cd angular-basic && npm install

生成的express项目目录

express

修改app.js的配置

  • 修改ejs: 文件扩展名ejs为html
  • 设置angular: 启动路径为”/”
  • 设置angular: 启动文件为app/index.html

~ vi app.js

var express = require('express')
    , path = require('path')
    , ejs = require('ejs')
    , app = express()
    , server = require('http').createServer(app);

app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.engine('.html', ejs.__express);
app.set('view engine', 'html'); //替换文件扩展名ejs为html
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'app')));

if (app.get('env') === 'development') {
    app.use(express.errorHandler());
}

// angular启动页
app.get('/', function (req, res) {
    res.sendfile('app/index.html');
});

server.listen(app.get('port'), function () {
    console.log('Express server listening on port ' + app.get('port'));
});

如何单独创建Express3的项目,请参考文章:Nodejs开发框架Express3.0开发手记–从零开始

2. 新建Angularjs目录及文件

创建Angularjs需要的目录及文件


D:\workspace\javascript\angular-basic>mkdir app
D:\workspace\javascript\angular-basic>mkdir app\scripts
D:\workspace\javascript\angular-basic>mkdir app\scripts\angular
D:\workspace\javascript\angular-basic>mkdir app\styles
D:\workspace\javascript\angular-basic>mkdir app\views
D:\workspace\javascript\angular-basic>mkdir app\views\component
D:\workspace\javascript\angular-basic>mkdir app\views\tpl

D:\workspace\javascript\angular-basic>touch app\index.html
D:\workspace\javascript\angular-basic>touch app\scripts\angular\app.js
D:\workspace\javascript\angular-basic>touch app\scripts\angular\controllers.js
D:\workspace\javascript\angular-basic>touch app\styles\main.css
D:\workspace\javascript\angular-basic>touch app\views\tpl\welcome.html

D:\workspace\javascript\angular-basic>echo "aaaa" > app\index.html

创建的Angularjs目录及文件

angular

目录解释:

  • app目录: Angular项目的根目录
  • scripts目录: 存放Javascript脚本目录
  • scripts\angular目录: 存放Angular Javascript脚本目录
  • styles目录: 存放css的目录
  • views目录: 存放html的目录
  • views\component目录: 存放html的自定义组件目录
  • views\tpl目录: 存放html的目录

文件解释:

  • app\index.html: Angular项目的入口文件
  • styles\main.css: Angular项目的css文件
  • scripts\angular\app.js: Angular项目全局配置文件
  • scripts\angular\controllers.js: Angular项目全局控制器文件/li>
  • views\tpl\welcome.html: 欢迎页

删除不需要的文件目录


D:\workspace\javascript\angular-basic>rm -rf public
D:\workspace\javascript\angular-basic>rm -rf routes

启动node服务器,检查入口页的配置


D:\workspace\javascript\angular-basic>node app.js
Express server listening on port 3000
GET / 200 11ms - 9b

indexpage

界面显示”aaaa”,说明node启动express,已经指向到app\index.html的页面。

3. 配置bower

接下来,我要通过bower来安装Angularjs和Bootstrap,以及其他依赖的前端库。关于bower的详细使用,请参考文章:bower解决js的依赖管理

新建文件:

    • .bowerrc: bower的环境设置,用于指定bower的依赖库的存放位置
    • bower.json: bower的依赖管理

新建文件: .bowerrc


~ vi .bowerrc

{
    "directory": "app/bower_components"
}

新建文件: bower.json


~ vi bower.json

{
    "name": "angular-basic",
    "version": "0.0.1",
    "dependencies": {
        "angular": "~1.2.12-build.2226",
        "angular-route": "~1.2.12-build.2226"
    },
    "devDependencies": {
    }
}

运行bower,下载Angular依赖库


D:\workspace\javascript\angular-basic>bower install
bower angular-route#~1.2.12-build.2226           cached git://github.com/angular/bower-angular-route.git#1.2.13-build.2242
bower angular-route#~1.2.12-build.2226         validate 1.2.13-build.2242 against git://github.com/angular/bower-angular-route.git#~1.2.12-build.2226
bower angular#~1.2.12-build.2226                 cached git://github.com/angular/bower-angular.git#1.2.13-build.2242
bower angular#~1.2.12-build.2226               validate 1.2.13-build.2242 against git://github.com/angular/bower-angular.git#~1.2.12-build.2226
bower angular#1.2.13-build.2242+sha.e645f7c      cached git://github.com/angular/bower-angular.git#1.2.13-build.2242
bower angular#1.2.13-build.2242+sha.e645f7c    validate 1.2.13-build.2242 against git://github.com/angular/bower-angular.git#1.2.13-build.2242+sha.e645f7c
bower angular-route#~1.2.12-build.2226          install angular-route#1.2.13-build.2242
bower angular#~1.2.12-build.2226                install angular#1.2.13-build.2242

angular-route#1.2.13-build.2242 app\bower_components\angular-route
└── angular#1.2.13-build.2242

angular#1.2.13-build.2242 app\bower_components\angular

下载最新版本的angular和angular-route,类库存放在app/bower_components目录下面。

bower-angular

4. 配置Angularjs项目

  • 修改index.html: 在入口文件,页面模板
  • 修改welcome.html: 欢迎页
  • 修改app.js: 全局配置
  • 修改controller.js: 控制器

修改index.html


<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8">
<title>Angular-basic</title>
<meta name="description" content="Copyright http://blog.fens.me">
<link rel="stylesheet" href="styles/main.css">
</head>
<body ng-app="app">

<ul>
<li><a href="http://blog.fens.me/angularjs-express3-bootstrap3/">快速搭建Web环境 Angularjs + Express3 + Bootstrap3</a></li>
<li>http://blog.fens.me/angularjs-express3-bootstrap3</li>
</ul>

<div ng-view></div>

<script src="bower_components/angular/angular.min.js"></script>
<script src="bower_components/angular-route/angular-route.min.js"></script>
<script src="scripts/angular/app.js"></script>
<script src="scripts/angular/controllers.js"></script>

</body>
</html>

修改welcome.html


Welcome {{ username }}

修改app.js


'use strict';

var app = angular.module('app', ['ngRoute']);

app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
    $routeProvider
        .when('/', {templateUrl: '/views/tpl/welcome.html', controller: 'WelcomeCtrl'})
        .otherwise({redirectTo: '/'});
    $locationProvider.html5Mode(true);
}]);

修改controller.js


'use strict';

function WelcomeCtrl($scope){
    $scope.username = 'Conan_Z';
}

重新启动node,查看Angular项目。


D:\workspace\javascript\angular-basic>node app.js
Express server listening on port 3000
GET / 304 8ms
GET /styles/main.css 304 3ms
GET /scripts/angular/app.js 304 6ms
GET /scripts/angular/controllers.js 304 11ms
GET /bower_components/angular-route/angular-route.min.js 200 18ms - 3.82kb
GET /bower_components/angular/angular.min.js 200 19ms - 98.03kb
GET /views/tpl/welcome.html 304 9ms
GET /bower_components/angular-route/angular-route.min.js.map 200 21ms - 9.61kb
GET /bower_components/angular/angular.min.js.map 200 26ms - 264.16kb

界面显示:

angular-start

index.html中配置的链接已经显示,同时welcome.html页面中配置的Welcome Conan_Z,也显示出来了。关于路由和模板配置,请参考文章:AngularJS路由和模板

5. 增加Bootstrap

接下来,增加Bootstrap-v3,让界面好看起来。我们还是有bower来管理Bootstrap的依赖。

通过命令行,增加类库,并写入的bower.json文件


D:\workspace\javascript\angular-basic>bower install bootstrap --save
D:\workspace\javascript\angular-basic>bower install angular-bootstrap --save
  • 修改index.html: 增加css, js的引用
  • 修改welcome.html: 增加bootstrap的效果

修改index.html


<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8">
<title>Angular-basic</title>
<meta name="description" content="Copyright http://blog.fens.me">
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="styles/main.css">
</head>
<body ng-app="app">

<div class="container">
<h2 class="text-primary">
<a href="http://blog.fens.me/angularjs-express3-bootstarp3/">快速搭建Web环境 Angularjs + Express3 + Bootstarp3</a>
</h2>
<p>http://blog.fens.me/angularjs-express3-bootstarp3</p>

<div class="row">
<div class=".col-lg-12">
<div ng-view></div>
</div>
</div>
</div>

<script src="bower_components/angular/angular.min.js"></script>
<script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="bower_components/angular-route/angular-route.min.js"></script>
<script src="bower_components/angular-bootstrap/ui-bootstrap-tpls.min.js"></script>
<script src="scripts/angular/app.js"></script>
<script src="scripts/angular/controllers.js"></script>

</body>
</html>

修改welcome.html


<hr/>
<form class="form-inline" role="form">
<div class="form-group">
<label>Welcome</label>
<input type="text" class="form-control" ng-model="username" placeholder="Enter email">
</div>
</form>
<p> {{ username }}</p>

angular-bootstrap

这样就用手动的方式的搭建了:Angularjs + Express3 + Bootstrap3的组合。

6. 完整的项目

项目代码已上传的github,项目地址: https://github.com/bsspirit/angular-basic

项目下载及安装


git clone https://github.com/bsspirit/angular-basic
npm install
bower install

项目运行


node app.js

当然,对于大型的Angular项目,我们可以选择用Yeoman的种子构建,请参考文章:AngularJS从构建项目开始

但有时Yeoman的项目,更新不够及时,比如bootstrap已到v3了,种子项目还是bootstrap的v2,而且v3不兼容v2。这时也许手动构建自己的项目,才是更好的选择。

转载请注明出处:
http://blog.fens.me/angularjs-express3-bootstrap3/

打赏作者

用Highcharts轻松构建交互性图表

从零开始nodejs系列文章,将介绍如何利Javascript做为服务端脚本,通过Nodejs框架web开发。Nodejs框架是基于V8的引擎,是目前速度最快的Javascript引擎。chrome浏览器就基于V8,同时打开20-30个网页都很流畅。Nodejs标准的web开发框架Express,可以帮助我们迅速建立web站点,比起PHP的开发效率更高,而且学习曲线更低。非常适合小型网站,个性化网站,我们自己的Geek网站!!

关于作者

  • 张丹(Conan), 程序员Java,R,PHP,Javascript
  • weibo:@Conan_Z
  • blog: http://blog.fens.me
  • email: bsspirit@gmail.com

转载请注明出处:
http://blog.fens.me/nodejs-highcharts/

nodejs-highcharts

前言

在大数据时代,数据可视化技术显得至关重要。一个设计优雅的信息图,能在一个600px*400px的画布上,显示出各种行业的全球市场的几百万条数据。

“如果图像能通过数据驱动,如果图像能动起来,如果图像支持交互,如果还能画股票K线图”,那才我想要的。Highchart是一个基于Javascript的跨浏览器的图形可视化工具,能满足我的需求。

目录

  1. highchart介绍
  2. highchart项目构建
  3. highchart使用
  4. highstock使用
  5. 项目源代码

1. highchart介绍

Highcharts是一个非常流行界面美观的纯Javascript图表库。它主要包括两个部分:Highcharts和Highstock。

Highcharts能够很简单便捷的在web网站或是web应用程序添加有交互性的图表,并且免费提供给个人学习、个人网站和非商业用途使用。目前HighCharts支持的图表类型有曲线图、区域图、柱状图、饼状图、散状点图和综合图表。

Highstock可以为您方便地建立股票或一般的时间轴图表。它包括先进的导航选项,预设的日期范围,日期选择器,滚动和平移等等。

官方网站:http://www.highcharts.com

中文资源:http://www.highcharts.me

2. highchart项目构建

系统环境

  • win7 64bit
  • Nodejs:v0.10.5
  • Npm:1.2.19

初始化项目


~ D:\workspace\javascript>mkdir highchart && cd highchart 

~ D:\workspace\javascript\highchart>bower search highchart
Search results:

    highcharts git://github.com/ewen/bower-highcharts.git
    highcharts.com git://github.com/highslide-software/highcharts.com.git
    angular-highcharts-directive git://github.com/rootux/angular-highcharts-directive.git
    highcharts-components git://github.com/nesbert/highcharts.git
    highcharts-ng git://github.com/pablojim/highcharts-ng.git
    angular-highcharts git://github.com/frapontillo/angular-highcharts.git

~ D:\workspace\javascript\highchart>bower install highcharts.com
bower highcharts.com#*      not-cached git://github.com/highslide-software/highcharts.com.git#*
bower highcharts.com#*         resolve git://github.com/highslide-software/highcharts.com.git#*
bower highcharts.com#*        download https://github.com/highslide-software/highcharts.com/archive/v3.0.7.tar.gz
bower highcharts.com#*         extract archive.tar.gz
bower highcharts.com#*        resolved git://github.com/highslide-software/highcharts.com.git#3.0.7
bower highcharts.com#~3.0.7    install highcharts.com#3.0.7

highcharts.com#3.0.7 bower_components\highcharts.com

我们通过bower来下载highchart库,有关bower的安装和使用,请参考文章:bower解决js的依赖管理

通过Ant工具构建highcharts. Ant是一个用Java开发的自动化构建工具。


~ cd bower_components\highcharts.com

~ ant build
Buildfile: D:\workspace\javascript\highchart\bower_components\highcharts.com\build.xml

set.properties:

clean:
    [mkdir] Created dir: D:\workspace\javascript\highchart\bower_components\highcharts.com\build
    [mkdir] Created dir: D:\workspace\javascript\highchart\bower_components\highcharts.com\build\dist\js\adapters
    [mkdir] Created dir: D:\workspace\javascript\highchart\bower_components\highcharts.com\build\dist\js\modules
    [mkdir] Created dir: D:\workspace\javascript\highchart\bower_components\highcharts.com\build\dist\highcharts\gfx
    [mkdir] Created dir: D:\workspace\javascript\highchart\bower_components\highcharts.com\build\dist\highcharts\js\adapters
    [mkdir] Created dir: D:\workspace\javascript\highchart\bower_components\highcharts.com\build\dist\highcharts\js\modules
    [mkdir] Created dir: D:\workspace\javascript\highchart\bower_components\highcharts.com\build\dist\highstock\gfx
    [mkdir] Created dir: D:\workspace\javascript\highchart\bower_components\highcharts.com\build\dist\highstock\js\adapters
    [mkdir] Created dir: D:\workspace\javascript\highchart\bower_components\highcharts.com\build\dist\highstock\js\modules
    [mkdir] Created dir: D:\workspace\javascript\highchart\bower_components\highcharts.com\build\tests
    [mkdir] Created dir: D:\workspace\javascript\highchart\bower_components\highcharts.com\build\coverage-report

assemble:

check-crlf:

do-lint:

lint:

minify:

compile:
     [echo] Minifying D:\workspace\javascript\highchart\bower_components\highcharts.com/js/highcharts.src.js
     [echo] Google Closure compiler: 463267 bytes -> 141575 bytes (52163 bytes zipped).
     [echo] Yahoo YUI Compressor: 463267 bytes -> 155872 bytes (57484 bytes zipped).
     [echo]
     [echo] Minifying D:\workspace\javascript\highchart\bower_components\highcharts.com/js/highstock.src.js
     [echo] Google Closure compiler: 579013 bytes -> 176349 bytes (64166 bytes zipped).
     [echo] Yahoo YUI Compressor: 579013 bytes -> 194135 bytes (70231 bytes zipped).
     [echo]
     [echo] Minifying D:\workspace\javascript\highchart\bower_components\highcharts.com/js/highcharts-more.src.js
     [echo] Google Closure compiler: 62849 bytes -> 21926 bytes (8265 bytes zipped).
     [echo] Yahoo YUI Compressor: 62849 bytes -> 22532 bytes (8682 bytes zipped).
     [echo]
     [echo] Minifying D:\workspace\javascript\highchart\bower_components\highcharts.com/js/highcharts-more.src.js
     [echo] Google Closure compiler: 62849 bytes -> 21926 bytes (8265 bytes zipped).
     [echo] Yahoo YUI Compressor: 62849 bytes -> 22532 bytes (8682 bytes zipped).
     [echo]
     [echo] Minifying D:\workspace\javascript\highchart\bower_components\highcharts.com/js/adapters/mootools-adapter.src.js
     [echo] Google Closure compiler: 8270 bytes -> 2406 bytes (1230 bytes zipped).
     [echo] Yahoo YUI Compressor: 8270 bytes -> 2338 bytes (1189 bytes zipped).
     [echo]
     [echo] Minifying D:\workspace\javascript\highchart\bower_components\highcharts.com/js/adapters/prototype-adapter.src.js
     [echo] Google Closure compiler: 9270 bytes -> 3330 bytes (1487 bytes zipped).
     [echo] Yahoo YUI Compressor: 9270 bytes -> 3251 bytes (1407 bytes zipped).
     [echo]
     [echo] Minifying D:\workspace\javascript\highchart\bower_components\highcharts.com/js/adapters/standalone-framework.src.js
     [echo] Google Closure compiler: 12261 bytes -> 5087 bytes (2328 bytes zipped).
     [echo] Yahoo YUI Compressor: 12261 bytes -> 5223 bytes (2318 bytes zipped).
     [echo]
     [echo] Minifying D:\workspace\javascript\highchart\bower_components\highcharts.com/js/modules/exporting.src.js
     [echo] Google Closure compiler: 18002 bytes -> 7264 bytes (3266 bytes zipped).
     [echo] Yahoo YUI Compressor: 18002 bytes -> 7204 bytes (3332 bytes zipped).
     [echo]
     [echo] Minifying D:\workspace\javascript\highchart\bower_components\highcharts.com/js/modules/data.src.js
     [echo] Google Closure compiler: 16086 bytes -> 4436 bytes (2048 bytes zipped).
     [echo] Yahoo YUI Compressor: 16086 bytes -> 4486 bytes (2066 bytes zipped).
     [echo]
     [echo] Minifying D:\workspace\javascript\highchart\bower_components\highcharts.com/js/modules/drilldown.src.js
     [echo] Google Closure compiler: 11421 bytes -> 5553 bytes (2109 bytes zipped).
     [echo] Yahoo YUI Compressor: 11421 bytes -> 5678 bytes (2161 bytes zipped).
     [echo]
     [echo] Minifying D:\workspace\javascript\highchart\bower_components\highcharts.com/js/modules/funnel.src.js
     [echo] Google Closure compiler: 6824 bytes -> 1974 bytes (1226 bytes zipped).
     [echo] Yahoo YUI Compressor: 6824 bytes -> 1885 bytes (1180 bytes zipped).
     [echo]
     [echo] Minifying D:\workspace\javascript\highchart\bower_components\highcharts.com/js/modules/no-data-to-display.src.js
     [echo] Google Closure compiler: 3009 bytes -> 1379 bytes (846 bytes zipped).
     [echo] Yahoo YUI Compressor: 3009 bytes -> 1185 bytes (729 bytes zipped).
     [echo]
     [echo] Minifying D:\workspace\javascript\highchart\bower_components\highcharts.com/js/modules/map.src.js
     [echo] Google Closure compiler: 34651 bytes -> 12719 bytes (5188 bytes zipped).
     [echo] Yahoo YUI Compressor: 34651 bytes -> 12889 bytes (5350 bytes zipped).
     [echo]
     [echo] Minifying D:\workspace\javascript\highchart\bower_components\highcharts.com/js/modules/heatmap.src.js
     [echo] Google Closure compiler: 1195 bytes -> 579 bytes (511 bytes zipped).
     [echo] Yahoo YUI Compressor: 1195 bytes -> 594 bytes (519 bytes zipped).
     [echo]
     [echo] Minifying D:\workspace\javascript\highchart\bower_components\highcharts.com/js/modules/annotations.src.js
     [echo] Google Closure compiler: 8776 bytes -> 3398 bytes (1668 bytes zipped).
     [echo] Yahoo YUI Compressor: 8776 bytes -> 3535 bytes (1777 bytes zipped).
     [echo]
     [echo] Minifying build/canvas-tools.src.js
     [echo] Google Closure compiler: 100698 bytes -> 57894 bytes (15848 bytes zipped).
     [echo] Yahoo YUI Compressor: 100698 bytes -> 59764 bytes (16054 bytes zipped).
     [echo]

BUILD SUCCESSFUL
Total time: 1 minute 19 seconds

在新生成的build/dist文件夹中,就能找到highchart.js, highstock.js,这两个用于发布的文件了。

highchart-build

用grunt创建一个静态服务器,grunt的使用说明,请参考文章:grunt让Nodejs规范起来

grunt的运行时环境,新建文件:package.json,Gruntfile.js


~ npm install grunt
~ npm install grunt-contrib-connect

~ vi packages.json
{
    "name": "nodejs-highcharts",
    "version": "0.0.1",
    "private": true,
    "scripts": {
        "start": "node app.js"
    },
    "dependencies": {
    },
    "devDependencies": {
        "grunt": "~0.4.1",
        "grunt-contrib-connect": "~0.4.1"
    }
}

~ vi Gruntfile.js
'use strict';
module.exports = function(grunt) {
    grunt.initConfig({
      connect: {
        server: {
          options: {
            port: 9001,
            base: './',
            keepalive: true
          }
        }
      }
    });

    grunt.loadNpmTasks('grunt-contrib-connect');
    grunt.registerTask('server', ['connect']);
};

新建一个测试文件:demo1.html


<!DOCTYPE html>
<html>
<head>
<title>HighCharts</title>
<script src="bower_components/highcharts.com/lib/jquery-1.10.1.js"></script>
<script src="bower_components/highcharts.com/build/dist/highcharts/js/highcharts.js"></script>
</head>
<body>

<div id="container" style="height: 400px"></div>
<script>
$(function () {
Highcharts.setOptions({
colors: ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4']
});

$('#container').highcharts({
chart: {
type: 'pie'
},

series: [{
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
}]
});
});
</script>
</body>
</html>

由于highcharts是依赖于jQuery的,所以我们也需要引入jquery.js

启动grunt server


~ D:\workspace\javascript\highchart>grunt server
Running "connect:server" (connect) task
Waiting forever...
Started connect web server on 127.0.0.1:9001.

浏览器打开:http://localhost:9001/demo1.html

highchart-pie

3. highchart使用

找到highchart的官网,查看demo:http://www.highcharts.com/demo/,支持好几十种可视化图形。

我最常用的是曲线图:

新建文件

  • line.html:网页文件
  • line.js:脚本文件,进行简单封装
  • line.json:数据文件

安装moment类库,用于时常日期转换

~ bower install moment

json/line.json


[
    {
        "name": "TF1312",
        "data": [
            [20131104091540,4.52],
            [20131104091600,4.51],
            [20131104091740,4.18],
            [20131104091843,4.26],
            [20131104091900,4.23],
            [20131104092053,4.2],
            [20131104092138,4.28],
            [20131104092256,4.83],
            [20131104092307,4.83],
            [20131104092439,4.88],
            [20131104092556,7.1],
            [20131104092623,7.12]
        ]
    },
    {
        "name": "TF1403",
        "data": [
            [20131104091540,4.23],
            [20131104091600,4.22],
            [20131104091740,4.11],
            [20131104091843,4.14],
            [20131104091900,4.13],
            [20131104092052,4.12],
            [20131104092126,4.15],
            [20131104092222,4.33],
            [20131104092306,4.35],
            [20131104092440,4.37],
            [20131104092556,5.1],
            [20131104092600,5.1]
        ]
    },
    {
        "name": "TF1406",
        "data": [
            [20131104091540,3.92],
            [20131104091600,3.92],
            [20131104091700,3.92],
            [20131104091800,3.92],
            [20131104091900,3.92],
            [20131104092052,3.88],
            [20131104092110,3.9 ],
            [20131104092254,3.8],
            [20131104092302,3.89],
            [20131104092400,3.9],
            [20131104092556,4.43],
            [20131104092634,4.44]
        ]
    }
]

line.html


<!DOCTYPE html>
<html>
<head>
<title>HighCharts - SplineChart</title>
<script src="bower_components/highcharts.com/lib/jquery-1.10.1.js"></script>
<script src="bower_components/moment/moment.js"></script>
<script src="bower_components/highcharts.com/build/dist/highcharts/js/highcharts.js"></script>
</head>
<body>
<div id="container" style="height: 400px"></div>
<script src="js/line.js"></script>
<script>
createSpline('#container','json/line.json',true);
</script>
</body>
</html>

js/line.js


/**
 * hightcharts global
 */
Highcharts.setOptions({
    global: {useUTC: false}
});

/**
 * my credits
 */
var defaultCredits = {
    href: 'http://blog.fens.me',
    position: {x: -30, y: -30},
    style: {color: '#191a37', fontWeight: 'bold'},
    text: 'http://blog.fens.me'
}

/**
 * transfer Datetime: 20130101101010 to time
 */
function transferDate(json) {
    for (var i = 0; i < json.length; i++) {
        var obj = json[i].data;
        for (var j = 0; j < obj.length; j++) {
            obj[j][0] = moment(obj[j][0], 'YYYYMMDDHHmmss').toDate().getTime();
        }
    }
    return json;
}

/**
 * Spline Chart Template
 */
function getSplineChart(series) {
    return {
        chart: {
            type: 'spline',
            animation: Highcharts.svg,
            marginRight: 10
        },
        title: {
            text: 'Title'
        },
        credits: defaultCredits,
        xAxis: {
            maxPadding: 0.05, minPadding: 0.05, type: 'datetime', tickWidth: 5,
            labels: {
                formatter: function() {
                    return Highcharts.dateFormat('%H:%M:%S', this.value);
                }
            }
        },
        yAxis: {
            title: {text: 'yAxis'},
            plotLines: [
                {value: 0, width: 1, color: '#808080'}
            ]
        },
        tooltip: {
            formatter: function () {
                return '<b>' + this.series.name + '</b><br/>' +
                    Highcharts.dateFormat('%H:%M:%S', this.x) + '<br/>' +
                    Highcharts.numberFormat(this.y, 2);
            }
        },
        legend: {enabled: true},
        exporting: {enabled: false},
        plotOptions: {
            spline: {
                lineWidth: 4, states: {hover: {lineWidth: 5}},
                marker: {enabled: false},
                pointInterval: 3600000,
                pointStart: Date.UTC(2009, 9, 6, 0, 0, 0)
            }
        },
        series: series
    };
}

/**
 * Create a spline
 */
function createSpline(id,url,transDate){
    $.get(url, function (json) {
        if(transDate||false) json=transferDate(json);
        $(id).highcharts(getSplineChart(json));
    });
}

查看效果图

highchart-line

4. highstock使用

到highchart的官网,查看stock demo:http://www.highcharts.com/stock/demo/,同样支持好多种可视化图形。

选择K线图(candlestick)实验:

新建文件:

  • candlestick.html:网页文件
  • candlestick.js:脚本文件,进行简单封装
  • candlestick.json:数据文件

json/candlestick.json, 部分数据


[
[1162771200000,78.95,80.06,78.43,79.71,15525782],
[1162857600000,80.45,81.00,80.13,80.51,18788494],
[1162944000000,80.02,82.69,79.89,82.45,24699702],
[1163030400000,82.90,84.69,82.12,83.34,32973747],
[1163116800000,83.55,83.60,82.50,83.12,13358721],
[1163376000000,83.22,84.45,82.64,84.35,16105532],
[1163462400000,84.80,85.00,83.90,85.00,21054939],
[1163548800000,85.05,85.90,84.00,84.05,23522893],
[1163635200000,84.87,86.30,84.62,85.61,24796743],
[1163721600000,85.14,85.94,85.00,85.85,16667310],
[1163980800000,85.40,87.00,85.20,86.47,20394365],
[1164067200000,87.42,88.60,87.11,88.60,22274133],
[1164153600000,88.99,90.75,87.85,90.31,24013531],
[1164326400000,89.53,93.08,89.50,91.63,18538136],
[1164585600000,92.51,93.16,89.50,89.54,38411382],
[1164672000000,90.36,91.97,89.91,91.81,37039840]
]

candlestick.html


<!DOCTYPE html>
<html>
<head>
<title>HighStock - Candlestick</title>
<script src="bower_components/highcharts.com/lib/jquery-1.10.1.js"></script>
<script src="bower_components/moment/moment.js"></script>
<script src="bower_components/highcharts.com/build/dist/highstock/js/highstock.js"></script>
</head>
<body>
<div id="container" style="height: 500px"></div>
<script src="js/candlestick.js"></script>
<script>
createCandlestick('#container','json/candlestick.json');
</script>
</body>
</html>

js/candlestick.js


/**
 * my credits
 */
var defaultCredits = {
    href: 'http://blog.fens.me',
    position: {x: -30, y: -30},
    style: {color: '#191a37', fontWeight: 'bold'},
    text: 'http://blog.fens.me'
}
/**
 * Paser Origin Data to Chart
 */
function paserStockData(data,transferDate){
    var ohlc = [],
        volume = [];

    for (var i = 0; i < data.length; i++) {
        if(transferDate||false){
            data[i][0] = moment(data[i][0], 'YYYYMMDDHHmmss').toDate().getTime();
        }

        ohlc.push([
            data[i][0], // the date
            data[i][1], // open
            data[i][2], // high
            data[i][3], // low
            data[i][4] // close
        ]);

        volume.push([
            data[i][0], // the date
            data[i][5] // the volume
        ])
    }

    var groupingUnits = [
        ['week',[1]],
        ['month',[1, 2, 3, 4, 5, 6]]
    ];

    var series=[{
        type: 'candlestick',
        name: 'Stock',
        data: ohlc,
        dataGrouping: {
            units: groupingUnits
        }
    }, {
        type: 'column',
        name: 'Volume',
        data: volume,
        yAxis: 1,
        dataGrouping: {
            units: groupingUnits
        }
    }];
    return series;
}

/**
 * Spline Chart Template
 */
function getCandlestick(series) {
    return {
        rangeSelector: {
            selected: 1
        },
        credits:defaultCredits,
        title: {
            text: 'Title'
        },
        yAxis: [{
            title: {
                text: 'Price'
            },
            height: 200,
            lineWidth: 2
        }, {
            title: {
                text: 'Volume'
            },
            top: 300,
            height: 100,
            offset: 0,
            lineWidth: 2
        }],
        series:series
    }
}

/**
* Create a Candlestick
*/
function createCandlestick(id,url,transDate){
    $.get(url, function (json) {
        json=paserStockData(json,transDate);
        $(id).highcharts('StockChart',getCandlestick(json));
    });
}

查看效果图
highchart-candlestick

5. 项目源代码

项目已经上传到github,感兴趣的同学自行下载。

https://github.com/bsspirit/highcharts-demo

转载请注明出处:
http://blog.fens.me/nodejs-highcharts/

打赏作者

Yeoman自动构建js项目

从零开始nodejs系列文章,将介绍如何利Javascript做为服务端脚本,通过Nodejs框架web开发。Nodejs框架是基于V8的引擎,是目前速度最快的Javascript引擎。chrome浏览器就基于V8,同时打开20-30个网页都很流畅。Nodejs标准的web开发框架Express,可以帮助我们迅速建立web站点,比起PHP的开发效率更高,而且学习曲线更低。非常适合小型网站,个性化网站,我们自己的Geek网站!!

关于作者

  • 张丹(Conan), 程序员Java,R,PHP,Javascript
  • weibo:@Conan_Z
  • blog: http://blog.fens.me
  • email: bsspirit@gmail.com

转载请注明出处:
http://blog.fens.me/nodejs-yeoman-intro/
yeoman

前言
有一种技术可以提高我们的工作效率,可以让我们专心做我们擅长的事,可以屏蔽复杂性,可以规范我们的架构和我们的代码,可以让我们的享受编程的乐趣。Yeoman可以做到。

很多年以前,rails刚刚出世,伴随着一个新的名词“脚手架(scaffolding)”出现了。脚手架是一种提高开发效率的工具的代名词。随后,各种编程语言都开始实现自己的“脚手架”工具。Maven重新构造了Java的世界,改变了几千万的开发者对于Java项目构建的认识。Yeoman在Javascript领域正做着同样的事情。

看着各种工具,各种语言,都在飞跃式的进化。做为一个开发者,我每天都在为变化而惊喜!

目录

  1. Yeoman介绍
  2. Yeoman工具包yo命令
  3. Yeoman工具包yo – 快速构建一个web项目
  4. Yeoman工具包bower,grunt的组合用法

1. Yeoman介绍

Yeoman是Google的团队和外部贡献者团队合作开发的,他的目标是通过Grunt(一个用于开发任务自动化的命令行工具)和Bower(一个HTML、CSS、Javascript和图片等前端资源的包管理器)的包装为开发者创建一个易用的工作流。

Yeoman主要有三部分组成:yo(脚手架工具)、grunt(构建工具)、bower(包管理器)。这三个工具是分别独立开发的,但是需要配合使用,来实现我们高效的工作流模式。

2. Yeoman工具包yo命令

yo插件都是通过npm, Node.js包管理器安装和管理的.

我的系统环境

  • win7 64bit
  • Nodejs:v0.10.5
  • Npm:1.2.19
~ D:\workspace\javascript>node -v
v0.10.5

~ D:\workspace\javascript>npm -v
1.2.19

在系统中,我们已经安装好了Nodejs和npm。win7安装nodejs请参考文章:Nodejs开发框架Express3.0开发手记–从零开始

全局安装yo

~ D:\workspace\javascript>npm install -g yo

如果你还没有安装grunt,bower,也需要一起安装

~ D:\workspace\javascript>npm install -g grunt-cli bower

接下我们看一下yo命令行操作
1). 通过help查看帮助


~ D:\workspace\javascript>yo --help
Yeoman is a mask worn by the following members of the open-source community:

  Paul Irish, Addy Osmani, Mickael Daniel, Sindre Sorhus, Eric Bidelman,
  Frederick Ros, Brian Ford, Pascal Hartig, Stephen Sawchuk, and countless
  other contributors.

Usage: yo GENERATOR [args] [options]

General options:
  -h, --help     # Print generator's options and usage
  -f, --force    # Overwrite files that already exist

Please choose a generator below.
Angular
  angular:app
  angular:common
  angular:constant
  angular:controller
  angular:decorator
  angular:directive
  angular:factory
  angular:filter
  angular:main
  angular:provider
  angular:route
  angular:service
  angular:value
  angular:view

Karma
  karma:app

Mocha
  mocha:app
  mocha:generator

Webapp
  webapp:app

yo的命令很简单:yo GENERATOR,例如:yo webapp, yo angular
Please choose a generator below: 下面列出了我的系统中,已经安装的generator的库,例如:Angular,Karma,Mocha,Webapp

2). 查询yo的支持库


~ D:\workspace\javascript>yo
Yeoman is a mask worn by the following members of the open-source community:

  Paul Irish, Addy Osmani, Mickael Daniel, Sindre Sorhus, Eric Bidelman,
  Frederick Ros, Brian Ford, Pascal Hartig, Stephen Sawchuk, and countless
  other contributors.

[?] What would you like to do? (Use arrow keys)
 > Install a generator
   Find some help
   Get me out of here!

命令行会提示,我们想要的操作。这里选择”Install a generator”


[?] What would you like to do? Install a generator
[?] Search NPM for generators:web

系统继续提示,我们要查找的包,我们输入web

3). 安装generator-webapp库


[?] Here's what I found. Install one? (Use arrow keys)
 > generator-armadillo
   generator-bones
   generator-btapp
   generator-fe
   generator-flight
   generator-hazdev-webapp
   generator-hbswebapp
   generator-html5-site
   generator-jing
   generator-lessapp
   generator-nodestrap
   generator-sails
   generator-server-configs
   generator-starter
   generator-starttter
   generator-ultimate
   generator-webapp
   generator-webapp-bfytw
   generator-webapp-fintan
   generator-weblog
   generator-website
   Search again
   Return home

yo列出了,所有在官方已经注册的,web关键字相关的包,我们选择“generator-webapp”

yo通过npm开始下载generator-webapp安装包


[?] What would you like to do? Install a generator
[?] Search NPM for generators: web
[?] Here's what I found. Install one? generator-webapp

generator-webapp@0.2.7 D:\toolkit\nodejs\node_modules\generator-webapp
├── cheerio@0.12.1 (entities@0.3.0, underscore@1.4.4, htmlparser2@3.1.4, cheerio-select@0.0.3)
└── yeoman-generator@0.12.3 (dargs@0.1.0, diff@1.0.5, debug@0.7.2, async@0.2.9, mime@1.2.11, mkdirp@0.3.5, isbinaryfi
le@0.1.9, underscore.string@2.3.3, shelljs@0.1.4, iconv-lite@0.2.11, lodash@1.3.1, rimraf@2.1.4, nopt@2.1.2, cli-table@0
.2.0, tar@0.1.18, glob@3.2.6, inquirer@0.2.4, request@2.21.0)

I just installed your generator by running:
    npm install -g generator-webapp

然后,我们退出yo命令行,选择“Get me out of here!”


[?] What would you like to do? Get me out of here!

Bye from us! Chat soon.
            Addy Osmani
          Sindre Sorhus
        Brian Ford
     Eric Bidelman
              Paul Irish
     Mickael Daniel
          Pasca1 Hartig
      Stephen S.wchuk
    Frederick R0s

上面的退出的文字是开发者的名字,很有意思一点是,竖着看最中间一行的文字排列是,yeoman1.0,也就是yeoman这个项目的得名了。

4). 注:上面的过程,也可以直接用命令

npm install -g generator-webapp

3. Yeoman工具包yo – 快速构建一个web项目

当我们安装了generator-webapp后,我们就可以,以非常优雅的方式来构建工程了。

1). 创建nodejs-yo目录,并构建webapp工程


~ D:\workspace\javascript>mkdir nodejs-yo
~ D:\workspace\javascript>cd nodejs-yo
~ D:\workspace\javascript\nodejs-yo>yo webapp

     _-----_
    |       |
    |--(o)--|   .--------------------------.
   `---------´  |    Welcome to Yeoman,    |
    ( _´U`_ )   |   ladies and gentlemen!  |
    /___A___\   '__________________________'
     |  ~  |
   __'.___.'__
 ´   `  |° ´ Y `

Out of the box I include HTML5 Boilerplate, jQuery and Modernizr.
[?] What more would you like?
  [ ] Twitter Bootstrap for Sass
 >[X] RequireJS
  [X] Autoprefixer for your CSS

对选项的解释:

  • Twitter Bootstrap for Sass:SASS是一种CSS的开发工具,提供了许多便利的写法,大大节省了设计者的时间,使得CSS的开发,变得简单和可维护。
  • RequireJS 可以帮助用户异步按需的加载 JavaScript 代码,并解决 JavaScript 模块间的依赖关系,提升了前端代码的整体质量和性能。
  • Autoprefixer解析CSS文件并且添加浏览器前缀到CSS规则里,使用Can I Use的数据来决定哪些前缀是需要的。

上面3个选择,由于Sass是基于Ruby的,我本机没有安装ruby,取消Twitter Bootstrap for Sass的勾选。

2). 查看安装日志:


Out of the box I include HTML5 Boilerplate, jQuery and Modernizr.
[?] What more would you like? RequireJS, Autoprefixer for your CSS
   create Gruntfile.js
   create package.json
   create .gitignore
   create .gitattributes
   create .bowerrc
   create bower.json
   create .jshintrc
   create .editorconfig
   create app/favicon.ico
   create app/404.html
   create app/robots.txt
   create app/.htaccess
   create app/styles/main.css
   create app/scripts/app.js
   create app/scripts/main.js
   create app/index.html
   create app/scripts/hello.coffee
   invoke   mocha:app
   create     test\index.html
   create     test\lib\chai.js
   create     test\lib\expect.js
   create     test\lib\mocha\mocha.css
   create     test\lib\mocha\mocha.js
   create     test\spec\test.js

I'm all done. Running bower install & npm install for you to install the required dependencies. If this fails, try running the command yourself.

项目骨架已经建好了。还包括了很多的配置文件.gitignore,bower.json,Gruntfile.js,favicon.ico, robots.txt, .htaccess。太神奇了,Cool!!

一下子装备都齐全了,打仗的事就交给我们自己吧。

4. Yeoman工具包bower,grunt的组合用法

有关bower的介绍,请参考:bower解决js的依赖管理
有关grunt的介绍,请参考:grunt让Nodejs规范起来

1). 使用bower命令查看项目依赖:


~ D:\workspace\javascript\nodejs-yo>bower list
bower check-new     Checking for new versions of the project dependencies..
nodejs-yo#0.0.0 D:\workspace\javascript\nodejs-yo
├── jquery#1.9.1 (latest is 2.0.3)
├── modernizr#2.6.2
└── requirejs#2.1.8

我们发现生成的webapp中,有4个依赖库,jquery,modernizr,requirejs。

2). 使用grunt命令执行单元测试


D:\workspace\javascript\nodejs-yo>grunt test
Running "clean:server" (clean) task
Cleaning ".tmp"...OK

Running "concurrent:test" (concurrent) task

Running "copy:styles" (copy) task

Running "coffee:dist" (coffee) task

Running "autoprefixer:dist" (autoprefixer) task
File ".tmp/styles/main.css" created.

Running "connect:test" (connect) task
Starting connect web server on localhost:9000.

Running "mocha:all" (mocha) task
Testing: http://localhost:9000/index.html

  .

  1 test complete (107 ms)

>> 1 passed! (0.11s)

Done, without errors.

3). 使用grunt命令启动一个node服务器


~ D:\workspace\javascript\nodejs-yo>grunt server
Running "server" task

Running "clean:server" (clean) task

Running "concurrent:server" (concurrent) task
    Warning: Running "compass:dist" (compass) task
Warning: You need to have Ruby and Compass installed and in your system PATH for this task to work. More info: https://g
ithub.com/gruntjs/grunt-contrib-compass Use --force to continue. Use --force to continue.

    Aborted due to warnings.

启动时,我们发现报错了。由于我没有装Ruby的环境,所以compass:dist的命令不能运行。

强制启动grunt


~ D:\workspace\javascript\nodejs-yo>grunt server --force
D:\workspace\javascript\nodejs-yo>grunt server --force
Running "server" task

Running "clean:server" (clean) task
Cleaning ".tmp"...OK

Running "concurrent:server" (concurrent) task

Running "coffee:dist" (coffee) task
    Warning: Running "compass:dist" (compass) task
Warning: You need to have Ruby and Compass installed and in your system PATH for this task to work. More info: https://
ithub.com/gruntjs/grunt-contrib-compass Use --force to continue. Used --force, continuing.

Running "compass:dist" (compass) task
Warning: You need to have Ruby and Compass installed and in your system PATH for this task to work. More info: https://
ithub.com/gruntjs/grunt-contrib-compass Use --force to continue.

Running "copy:styles" (copy) task

Running "autoprefixer:dist" (autoprefixer) task
File ".tmp/styles/main.css" created.

Running "connect:livereload" (connect) task
Starting connect web server on localhost:9000.

Running "open:server" (open) task

Running "watch" task
Waiting...

后台日志显示了“watch”的task,说明代码文件被监控着,如有修改网页会自动更新。

浏览器被自动打开,http://localhost:9000/
yeoman1

4). 修改app/index.html代码,增加对canvas的检查。


~ vi app/index.html

<script>
window.onload = function () {
if (canvasSupported()) {
alert('canvas supported');
}
};

function canvasSupported() {
var canvas = document.createElement('canvas');
return (canvas.getContext && canvas.getContext('2d'));
}
</script>

浏览器显示:
yeoman2

5). 通过bower增加库jquery-pjax


~ D:\workspace\javascript\nodejs-yo>bower install jquery-pjax
bower jquery-pjax#*         not-cached git://github.com/defunkt/jquery-pjax.git#*
bower jquery-pjax#*            resolve git://github.com/defunkt/jquery-pjax.git#*
bower jquery-pjax#*           download https://github.com/defunkt/jquery-pjax/archive/v1.7.3.tar.gz
bower jquery-pjax#*            extract archive.tar.gz
bower jquery-pjax#*           resolved git://github.com/defunkt/jquery-pjax.git#1.7.3
bower jquery#>=1.8              cached git://github.com/components/jquery.git#2.0.3
bower jquery#>=1.8            validate 2.0.3 against git://github.com/components/jquery.git#>=1.8
bower jquery-pjax#~1.7.3       install jquery-pjax#1.7.3

jquery-pjax#1.7.3 app\bower_components\jquery-pjax
└── jquery#2.0.3

~ D:\workspace\javascript\nodejs-yo>bower list
bower check-new     Checking for new versions of the project dependencies..
nodejs-yo#0.0.0 D:\workspace\javascript\nodejs-yo
├── jquery#1.9.1 (latest is 2.0.3)
├─┬ jquery-pjax#1.7.3 extraneous
│ └── jquery#1.9.1 (2.0.3 available)
├── modernizr#2.6.2
└── requirejs#2.1.8

Yeoman已经成功地帮助我们打造出一个项目的原型了,接下来我们可以针对自己的项目,自己熟悉的框架组合,构建一个属于自己的骨架模板,并发布到Yeoman的generator库中。

后面的内容会更精彩,敬请期待…!!

转载请注明出处:
http://blog.fens.me/nodejs-yeoman-intro/

打赏作者

bower解决js的依赖管理

从零开始nodejs系列文章,将介绍如何利Javascript做为服务端脚本,通过Nodejs框架web开发。Nodejs框架是基于V8的引擎,是目前速度最快的Javascript引擎。chrome浏览器就基于V8,同时打开20-30个网页都很流畅。Nodejs标准的web开发框架Express,可以帮助我们迅速建立web站点,比起PHP的开发效率更高,而且学习曲线更低。非常适合小型网站,个性化网站,我们自己的Geek网站!!

关于作者

  • 张丹(Conan), 程序员Java,R,PHP,Javascript
  • weibo:@Conan_Z
  • blog: http://blog.fens.me
  • email: bsspirit@gmail.com

转载请注明出处:
http://blog.fens.me/nodejs-bower-intro/

bower

前言
一个新的web项目开始,我们总是很自然地去下载需要用到的js类库文件,比如jQuery,去官网下载名为jquery-1.10.2.min.js文件,放到我们的项目里。当项目又需要bootstrap的时候,我们会重复刚才的工作,去bootstrap官网下载对应的类库。如果bootstrap所依赖的jQuery并不是1.10.2,而是2.0.3时,我们会再重新下载一个对应版本的jQuery替换原来的。

包管理是个复杂的问题,我们要知道谁依赖谁,还要明确哪个版本依赖哪个版本。这些对于开发人员来说,负担过重了。bower作为一个js依赖管理的工具,提供一种理想包管理方式,借助了npm的一些思想,为我们提供一个舒服的开发环境。

你要还不动起手来试试bower,那你一定不会知道,前端开发是件多么享受的事。

目录

  1. bower介绍
  2. bower安装
  3. bower命令
  4. bower使用
  5. 用bower提交自己类库

1. bower介绍

Bower 是 twitter 推出的一款包管理工具,基于nodejs的模块化思想,把功能分散到各个模块中,让模块和模块之间存在联系,通过 Bower 来管理模块间的这种联系。

包管理工具一般有以下的功能:

  • 注册机制:每个包需要确定一个唯一的 ID 使得搜索和下载的时候能够正确匹配,所以包管理工具需要维护注册信息,可以依赖其他平台。
  • 文件存储:确定文件存放的位置,下载的时候可以找到,当然这个地址在网络上是可访问的。
  • 上传下载:这是工具的主要功能,能提高包使用的便利性。比如想用 jquery 只需要 install 一下就可以了,不用到处找下载。上传并不是必备的,根据文件存储的位置而定,但需要有一定的机制保障。
  • 依赖分析:这也是包管理工具主要解决的问题之一,既然包之间是有联系的,那么下载的时候就需要处理他们之间的依赖。下载一个包的时候也需要下载依赖的包。

功能介绍,摘自文章:http://chuo.me/2013/02/twitter-bower.html

2. bower安装

bower插件是通过npm, Node.js包管理器安装和管理的.

我的系统环境

  • win7 64bit
  • Nodejs:v0.10.5
  • Npm:1.2.19
~ D:\workspace\javascript>node -v
v0.10.5

~ D:\workspace\javascript>npm -v
1.2.19

在系统中,我们已经安装好了Nodejs和npm。win7安装nodejs请参考文章:Nodejs开发框架Express3.0开发手记–从零开始

安装bower
全局安装bower


~ D:\workspace\javascript>npm install bower -g

新建一个express3的项目nodejs-bower


~ D:\workspace\javascript>express -e nodejs-bower
~ D:\workspace\javascript>cd nodejs-bower && npm install

3. bower命令

bower安装后,我们就可以用bower这个命令了。

~ D:\workspace\javascript\nodejs-bower>bower
Usage:
    bower  [] []
Commands:
    cache                   Manage bower cache
    help                    Display help information about Bower
    home                    Opens a package homepage into your favorite browser
    info                    Info of a particular package
    init                    Interactively create a bower.json file
    install                 Install a package locally
    link                    Symlink a package folder
    list                    List local packages
    lookup                  Look up a package URL by name
    prune                   Removes local extraneous packages
    register                Register a package
    search                  Search for a package by name
    update                  Update a local package
    uninstall               Remove a local package
Options:
    -f, --force             Makes various commands more forceful
    -j, --json              Output consumable JSON
    -l, --log-level         What level of logs to report
    -o, --offline           Do not hit the network
    -q, --quiet             Only output important information
    -s, --silent            Do not output anything, besides errors
    -V, --verbose           Makes output more verbose
    --allow-root            Allows running commands as root
See 'bower help ' for more information on a specific command.

Commands,列出了bower支持的各种命令。

  • cache:bower缓存管理
  • help:显示Bower命令的帮助信息
  • home:通过浏览器打开一个包的github发布页
  • info:查看包的信息
  • init:创建bower.json文件
  • install:安装包到项目
  • link:在本地bower库建立一个项目链接
  • list:列出项目已安装的包
  • lookup:根据包名查询包的URL
  • prune:删除项目无关的包
  • register:注册一个包
  • search:搜索包
  • update:更新项目的包
  • uninstall:删除项目的包

4. bower使用

1). 安装jQuery到项目nodejs-bower


~ D:\workspace\javascript\nodejs-bower>bower install jquery
bower jquery#*              not-cached git://github.com/components/jquery.git#*
bower jquery#*                 resolve git://github.com/components/jquery.git#*
bower jquery#*                download https://github.com/components/jquery/archive/2.0.3.tar.gz
bower jquery#*                 extract archive.tar.gz
bower jquery#*                resolved git://github.com/components/jquery.git#2.0.3
bower jquery#~2.0.3            install jquery#2.0.3

jquery#2.0.3 bower_components\jquery

通过执行命令,我们可以看到jQuery的最新版本被下载,并安装到项目的bower_components\jquery目录

查看bower_components/jquery目录,发现了3个文件。


~ D:\workspace\javascript\nodejs-bower>ls bower_components/jquery -a
.  ..  .bower.json  component.json  jquery.js

同样地,我们的项目还需要d3的类库


~ D:\workspace\javascript\nodejs-bower>bower install d3
bower d3#*                  not-cached git://github.com/mbostock/d3.git#*
bower d3#*                     resolve git://github.com/mbostock/d3.git#*
bower d3#*                    download https://github.com/mbostock/d3/archive/v3.2.8.tar.gz
bower d3#*                     extract archive.tar.gz
bower d3#*                    resolved git://github.com/mbostock/d3.git#3.2.8
bower d3#~3.2.8                install d3#3.2.8

d3#3.2.8 bower_components\d3

非常方便,下载并安装完成!

2). 查看项目中已导入的类库


~ D:\workspace\javascript\nodejs-bower>bower list
bower check-new     Checking for new versions of the project dependencies..
nodejs-bower#0.0.0 D:\workspace\javascript\nodejs-bower
├── d3#3.2.8
└── jquery#2.0.3

3). 安装bootstrap库,并查看依赖情况


~ D:\workspace\javascript\nodejs-bower>bower install bootstrap
bower bootstrap#*               cached git://github.com/twbs/bootstrap.git#3.0.0-rc1
bower bootstrap#*             validate 3.0.0-rc1 against git://github.com/twbs/bootstrap.git#*
bower jquery#>= 1.9.0           cached git://github.com/components/jquery.git#2.0.3
bower jquery#>= 1.9.0         validate 2.0.3 against git://github.com/components/jquery.git#>= 1.9.0
bower bootstrap#~3.0.0-rc1     install bootstrap#3.0.0-rc1

bootstrap#3.0.0-rc1 bower_components\bootstrap
└── jquery#2.0.3

~ D:\workspace\javascript\nodejs-bower>bower list
bower check-new     Checking for new versions of the project dependencies..
nodejs-bower#0.0.0 D:\workspace\javascript\nodejs-bower
├─┬ bootstrap#3.0.0-rc1 extraneous
│ └── jquery#2.0.3
├── d3#3.2.8
└── jquery#2.0.3

我们发现bootstrap,对jquery是有依赖的。

4). 删除jQuery库,破坏依赖关系


~ D:\workspace\javascript\nodejs-bower>bower uninstall jquery
bower conflict      bootstrap depends on jquery
Continue anyway? (y/n) y
bower uninstall     jquery

~ D:\workspace\javascript\nodejs-bower>bower list
bower check-new     Checking for new versions of the project dependencies..
nodejs-bower#0.0.0 D:\workspace\javascript\nodejs-bower
├─┬ bootstrap#3.0.0-rc1 extraneous
│ └── jquery missing
├── d3#3.2.8
└── jquery missing

5). 安装低版本的jQuery,制造不版本兼容


~ D:\workspace\javascript\nodejs-bower>bower install jquery#1.7.2
bower jquery#~2.0.3             cached git://github.com/components/jquery.git#2.0.3
bower jquery#~2.0.3           validate 2.0.3 against git://github.com/components/jquery.git#~2.0.3
bower jquery#>= 1.9.0           cached git://github.com/components/jquery.git#2.0.3
bower jquery#>= 1.9.0         validate 2.0.3 against git://github.com/components/jquery.git#>= 1.9.0
bower jquery#1.7.2              cached git://github.com/components/jquery.git#1.7.2
bower jquery#1.7.2            validate 1.7.2 against git://github.com/components/jquery.git#1.7.2

Unable to find a suitable version for jquery, please choose one:
    1) jquery#1.7.2 which resolved to 1.7.2
    2) jquery#~2.0.3 which resolved to 2.0.3 and has nodejs-bower as dependants
    3) jquery#>= 1.9.0 which resolved to 2.0.3 and has bootstrap#3.0.0-rc1 as dependants

Prefix the choice with ! to persist it to bower.json

Choice: 1
bower jquery#1.7.2             install jquery#1.7.2

jquery#1.7.2 bower_components\jquery

~ D:\workspace\javascript\nodejs-bower>bower list
bower check-new     Checking for new versions of the project dependencies..
nodejs-bower#0.0.0 D:\workspace\javascript\nodejs-bower
├─┬ bootstrap#3.0.0-rc1 extraneous
│ └── jquery#1.7.2 incompatible with >= 1.9.0 (2.0.3 available)
├── d3#3.2.8
└── jquery#1.7.2 incompatible with ~2.0.3 (2.0.3 available)

我们可以清楚的看到bower,很明确的告诉了我们,jquery和bootstrap是不兼容的,强大之处大家应该有所体会。

6).升级jQuery,让版本兼容


~ D:\workspace\javascript\nodejs-bower>bower update jquery
bower jquery#~2.0.3             cached git://github.com/components/jquery.git#2.0.3
bower jquery#~2.0.3           validate 2.0.3 against git://github.com/components/jquery.git#~2.0.3
bower jquery#>= 1.9.0           cached git://github.com/components/jquery.git#2.0.3
bower jquery#>= 1.9.0         validate 2.0.3 against git://github.com/components/jquery.git#>= 1.9.0
bower jquery#~2.0.3            install jquery#2.0.3

jquery#2.0.3 bower_components\jquery

~ D:\workspace\javascript\nodejs-bower>bower list
bower check-new     Checking for new versions of the project dependencies..
nodejs-bower#0.0.0 D:\workspace\javascript\nodejs-bower
├─┬ bootstrap#3.0.0-rc1 extraneous
│ └── jquery#2.0.3
├── d3#3.2.8
└── jquery#2.0.3

多么智能,一键搞定,这才是高效的开发。

7). 查看本地bower已经缓存的类库


~ D:\workspace\javascript\nodejs-bower>bower cache list
bootstrap=git://github.com/twbs/bootstrap.git#3.0.0-rc1
d3=git://github.com/mbostock/d3.git#3.2.8
jquery=git://github.com/components/jquery.git#1.7.2
jquery=git://github.com/components/jquery.git#2.0.3

8). 查看D3库信息


~ D:\workspace\javascript\nodejs-bower>bower info d3
d3

  Versions:
    - 3.2.8
    - 3.2.7
    - 3.2.6
    - 3.2.5
    - 3.2.4
    - 3.2.3
    ...

9). 查看dojo库的url


~ D:\workspace\javascript\nodejs-bower>bower lookup dojo
dojo git://github.com/dojo/dojo.git

10). 用浏览器打开dojo的发布主页


~ D:\workspace\javascript\nodejs-bower>bower home dojo
bower dojo#*                not-cached git://github.com/dojo/dojo.git#*
bower dojo#*                   resolve git://github.com/dojo/dojo.git#*
bower dojo#*                  download https://github.com/dojo/dojo/archive/1.9.1.tar.gz
bower dojo#*                   extract archive.tar.gz
bower dojo#*                  resolved git://github.com/dojo/dojo.git#1.9.1

浏览器自动打开:https://github.com/dojo/dojo

11). 查询包含dojo的类库


~ D:\workspace\javascript\nodejs-bower>bower search dojo
Search results:

    dojo git://github.com/dojo/dojo.git
    dojox git://github.com/dojo/dojox.git
    dojo-util git://github.com/dojo/util.git
    dojo-bootstrap git://github.com/samvdb/Dojo-Bootstrap

真是方便实用的技术。

5. 用bower提交自己类库

1). 生成bower.json配置文件


~ D:\workspace\javascript\nodejs-bower>bower init
bower existing      The existing bower.json file will be used and filled in
[?] name: nodejs-bower
[?] version: 0.0.0
[?] main file:
[?] set currently installed components as dependencies? No
[?] add commonly ignored files to ignore list? Yes

查看生成的文件bower.json


{
  "name": "nodejs-bower",
  "version": "0.0.0",
  "ignore": [
    "**/.*",
    "node_modules",
    "bower_components",
    "test",
    "tests"
  ],
  "dependencies": {
    "d3": "git://github.com/mbostock/d3.git#~3.2.8",
    "jquery": "git://github.com/components/jquery.git#~2.0.3"
  }
}

2). 在github创建一个资源库:nodejs-bower
3). 本地工程绑定github


~ D:\workspace\javascript\nodejs-bower>git init
Initialized empty Git repository in D:/workspace/javascript/nodejs-bower/.git/

~ D:\workspace\javascript\nodejs-bower>git add .
~ D:\workspace\javascript\nodejs-bower>git commit -m "first commit"
# On branch master
#
# Initial commit
#
# Untracked files:
#   (use "git add ..." to include in what will be committed)
#
#       app.js
#       bower.json
#       bower_components/
#       node_modules/
#       package.json
#       public/
#       routes/
#       views/
nothing added to commit but untracked files present (use "git add" to track)

~ D:\workspace\javascript\nodejs-bower>git remote add origin https://github.com/bsspirit/nodejs-bower

~ D:\workspace\javascript\nodejs-bower>git push -u origin master
Counting objects: 565, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (516/516), done.
Writing objects: 100% (565/565), 803.08 KiB, done.
Total 565 (delta 26), reused 0 (delta 0)
To https://github.com/bsspirit/nodejs-bower
 * [new branch]      master -> master
Branch master set up to track remote branch master from origin.

4). 注册到bower官方类库


~ D:\workspace\javascript\nodejs-bower>bower register nodejs-bower git@github.com:bsspirit/nodejs-bower.git
bower                          convert Converted git@github.com:bsspirit/nodejs-bower.git to git://github.com/bsspirit/n
odejs-bower.git
bower nodejs-bower#*           resolve git://github.com/bsspirit/nodejs-bower.git#*
bower nodejs-bower#*          checkout master
bower nodejs-bower#*          resolved git://github.com/bsspirit/nodejs-bower.git#af3ceaac07
Registering a package will make it visible and installable via the registry (https://bower.herokuapp.com), continue? (y/
n)                    y
bower nodejs-bower            register git://github.com/bsspirit/nodejs-bower.git

Package nodejs-bower registered successfully!
All valid semver tags on git://github.com/bsspirit/nodejs-bower.git will be available as versions.
To publish a new version, you just need release a valid semver tag.

Run bower info nodejs-bower to list the package versions.

5). 查询我们自己的包


D:\workspace\javascript\nodejs-bower>bower search nodejs-bower
Search results:

    nodejs-bower git://github.com/bsspirit/nodejs-bower.git

6). 安装我们自己的包


D:\workspace\javascript\nodejs-bower>bower install nodejs-bower
bower nodejs-bower#*            cached git://github.com/bsspirit/nodejs-bower.git#af3ceaac07
bower nodejs-bower#*          validate af3ceaac07 against git://github.com/bsspirit/nodejs-bower.git#*
bower nodejs-bower#*           install nodejs-bower#af3ceaac07

nodejs-bower#af3ceaac07 bower_components\nodejs-bower
├── d3#3.2.8
└── jquery#2.0.3

其实模块化,版本依赖,开发类库,发布类库,安装类库,都是一条命令!还能再简单一点么!快把项目模块化,然后分享给大家吧!!未来是属于开发者的。

转载请注明出处:
http://blog.fens.me/nodejs-bower-intro/

打赏作者