我曾经尝试使用 grunt,但是当配置变大时,我发现自己对 grunt 的配置感到很困惑。我会尝试通过使用gulp 为您的前端构建工具提供建议。它更简单,更容易阅读和更快。您可以阅读差异here。
几乎相同,虽然 grunt 在 gruntfile.js 中指定了所有配置,但 gulp 在 gulpfile.js 中指定了它的配置。通常我会在我命名为gulpfile.config.js 的额外文件中创建自己的配置。它看起来像这样:
gulpfile.config.js
module.exports = {
development: {
css: [
'./development/bower_components/bootstrap/dist/css/bootstrap.min.css',
'./development/bower_components/font-awesome/css/font-awesome.min.css'
],
js: [
'./development/bower_components/angular/angular.min.js',
'./development/app/components/*.js',
'./development/app/components/**/*.js'
],
ENV: {
name: 'development'
}
},
production: {
css: ['./production/dist/css/app.min.css'],
js: ['./production/dist/js/app.min.js'],
ENV: {
name: 'production'
}
}
}
在 gulpfile.js 中,我可以简单地根据我在 gulpfile.config.js 中配置的环境运行任务
var config = require('./gulpfile.config.js'),
gulp = require('gulp'),
cleancss = require('gulp-clean-css');
gulp.task('scripts', function() {
return gulp.src(config.development.js)
.pipe(concat('app.js'))
.pipe(ngannotate())
.pipe(rename({suffix: '.min'}))
.pipe(uglify())
.pipe(gulp.dest(config.ENV.name + '/dist/js'))
});
就像 grunt 一样,gulp 提供了大量很酷的插件来构建您的前端应用程序。我自己通常使用 gulp-less、gulp-minify-css、gulp-ng-annotate、gulp-uglify、gulp-concat、gulp-server-livereload、gulp-rename、gulp-inject、gulp-imagemin。当然,您可以探索许多其他插件。希望这可以帮助!
[更新 - 基于环境构建 index.html]
首先你需要配置任务并且需要所有的 gulp 插件
var config = require('./gulpfile.config.js'),
gulp = require('gulp'),
del = require('del'),
inject = require('gulp-inject'),
rename = require('gulp-rename'),
gulpif = require('gulp-if'),
argv = require('yargs').argv;
if (argv.production) {
var selectedConfig = config.production;
} else {
var selectedConfig = config.development;
}
gulp.task('index', function() {
return gulp.src('./development/assets/templates/index.tpl.html')
.pipe(inject(gulp.src(selectedConfig.css.concat(selectedConfig.js), {read: false}), {ignorePath: selectedConfig.ENV.name}))
.pipe(rename('index.html'))
.pipe(gulp.dest(selectedConfig.ENV.name));
})
并提供index.tpl.html
<!DOCTYPE html>
<html>
<head>
<!-- inject:css -->
<!-- endinject -->
</head>
<body>
<!-- inject:js -->
<!-- endinject -->
</body>
</html>
然后您可以通过运行gulp index --development 或gulp index --production 来简单地构建index.html