这几天看了几个前端包管理器:seajs,browserfiy,duo等。结合nodejs的学习,用duo最适合练手。
目的:用duo,gulp管理前端项目
index.js
var uid = require('matthewmueller/uid');
var template = require('./lib/template.js');
var data = require('./tmpl/content.html');
var render = template.compile(data);
var html = render({user: 'techfellow', uid: uid()});
$('.wrapper').append(html);
这里面用到了:
引用github库:uid
引用本地库:template.js(支持AMD加载的都可以用)
引用本地模板:content.html
引用其它库:jquery
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="">
</head>
<body>
<div class="wrapper"></div>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="build/index.js?rev=@@hash"></script>
</body>
</html>
这里面,wrapper将插入模板,rev=@@hash将替换为哈希值。
写下模板内容:
tmpl/content.html
<div>
Hello, {{user}}! Your ID is: {{uid}}
</div>
基本完成了。
在项目目录下执行:
duo index.js
会生成build/index.js。
运行看看效果:
Hello, techfellow! Your ID is: ovdnol9
加上gulp的压缩、混淆、版本控制功能:
gulpfile.js
var gulp = require('gulp'),
htmlmin = require('gulp-htmlmin'),
cssmin = require('gulp-minify-css'),
jsmin = require('gulp-uglify'),
rev = require('gulp-rev-append');
gulp.task('html', function() {
var options = {
removeComments: true, //清除HTML注释
collapseWhitespace: true, //压缩HTML
collapseBooleanAttributes: true, //省略布尔属性的值 <input checked="true"/> ==> <input />
removeEmptyAttributes: true, //删除所有空格作属性值 <input id="" /> ==> <input />
removeScriptTypeAttributes: true, //删除<script>的type="text/javascript"
removeStyleLinkTypeAttributes: true, //删除<style>和<link>的type="text/css"
minifyJS: true, //压缩页面JS
minifyCSS: true //压缩页面CSS
};
gulp.src(['src/**/*.html', '!src/tmpl/*.html', '!src/components/**/*.html'])
.pipe(rev())
.pipe(htmlmin(options))
.pipe(gulp.dest('dest'));
});
gulp.task('css', function() {
gulp.src('src/**/*.css')
.pipe(cssmin())
.pipe(gulp.dest('dest'));
});
gulp.task('js', function() {
gulp.src('src/build/**/*.js')
.pipe(jsmin())
.pipe(gulp.dest('dest/build'));
});
gulp.task('image', function() {
gulp.src('src/images/*')
.pipe(gulp.dest('dest/images/'));
gulp.src('src/static/**/*.{png,jpg,gif}')
.pipe(gulp.dest('dest/static'));
});
gulp.task('default', ['image', 'html', 'css', 'js']);
dest/index.html
<script src="build/index.js?rev=88932f41b1ece4b995c4f6adc34deed3"></script>