我正在努力解决以下问题:
我的 gulpfile.js 编译所有 .less,缩小它并将所有 CSS 连接到 ./dist/all.min.css
有没有一种方法可以重写 HTML 文件,删除所有样式标签,然后只将一个样式标签放入其中加载缩小的 CSS?
最佳答案
处理这个问题的最好方法是从一开始就使用其中一个 HTML 注入(inject)器。我正在使用 gulp-inject
到目前为止取得了一些成功。
添加 gulp-inject到您的项目:
npm i --save-dev gulp-inject
假设您有一个类似于此的文件夹布局:
您的 HTML 应该在您希望注入(inject) CSS 或 JS 文件的位置包含此内容,或者两者的头部,或者 CSS 的头部以及 JS 文件的正文之前:
<!-- inject:css -->
<!-- any *.css files among your sources will go here as: <link rel="stylesheet" href="FILE"> -->
<!-- endinject -->
<!-- inject:js -->
<!-- any *.js files among your sources will go here as: <script src="FILE"></script> -->
<!-- endinject -->
然后你的 gulpfile 看起来像这样:
gulp.task('build-styles', function() {
// the return is important!
return gulp.src('src/less/main.less')
.pipe(less())
.pipe(gulp.dest('build'));
});
gulp.task('build-js', function() {
// the return is important if you want proper dependencies!
return gulp.src('src/js/**/*.js')
// lint, process, whatever
.pipe(gulp.dest('build'));
});
gulp.task('build-html', function() {
// We src all files under build
return gulp.src('build/**/*.*')
// and inject them into the HTML
.pipe(inject('src/index.html', {
addRootSlash: false, // ensures proper relative paths
ignorePath: '/build/' // ensures proper relative paths
}))
.pipe(gulp.dest('build'));
});
gulp.task('build', ['build-styles', 'build-js'], function(cb) {
gulp.run('build-html', cb);
});
gulp.task('default', ['build'], function() {
gulp.watch('src/**/*.less', function() {
gulp.run('build-styles');
});
gulp.watch(['build/**/*.*','!build/index.html', 'src/index.html'], function() {
gulp.run('build-html');
});
});
这只是一个粗略的想法,您可以使用
gulp-watch
做更多的事情对于增量构建,但这里的关键是我们观察构建目录以选择何时重建 HTML 文件,并观察 src 目录中的所有其他内容。NOTE:
Since this is getting a lot of upvotes, there are a couple other plugins that do reference replacement beside
gulp-inject
. You may want to look at them and see if one of them is a better fit for you, especially if you are not usinggulp-rev
:There are also two CDN libraries that do a similar thing, but for CDN resources
- gulp-google-cdn
- gulp-cdnizer (full disclosure: I wrote this one)
关于concatenation - 有没有办法重写 HTML 以使用 gulp-minified CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21072880/