![](/img/trans.png)
[英]Generate Critical CSS for every *.HTML file using critical and Gulp
[英]Generate critical CSS for all .html pages with Gulp
因此,Google建議使用以下npm軟件包來生成關鍵的CSS:
var critical = require('critical');
gulp.task('critical', function (cb) {
critical.generate({
base: 'app/',
src: 'index.html',
dest: 'css/index.css'
});
});
它實際上是一個很棒的工具,就像一個魅力。 唯一的缺點是,它只適用於Gulp中的單個文件,而不是可以對所有匹配文件使用gulp.src('app/*.html')
調用的其他任務。
因此,我決定將我的所有頁面列出在一個數組中並對其進行遍歷:
var pages = ['index', 'pricing'];
gulp.task('critical', function (cb) {
for (var i = 0; i < pages.length; i++) {
critical.generate({
base: 'app/',
src: pages[i] + '.html',
dest: 'css/' + pages[i] + '.css'
});
}
});
事實證明,這也是一個可行的解決方案(某些node.js內存問題除外)。
現在的問題是我必須在陣列中手動列出頁面。 因此,我想知道是否有一種方法可以使用類似於gulp.src('app/*.html')
的功能自動生成這樣的列表,例如將選定文件夾中的所有.html頁面包括在內,以生成重要的CSS?
任何幫助將不勝感激!
您可以做類似的事情(后面是偽代碼):
var foreach = require('gulp-foreach');
gulp.task('default', function () {
return gulp.src('./yourPathTo/*.html')
// treats each file in gulp.src as a separate stream
.pipe(foreach(function (stream, file) {
// see in next code for example of following
var fileBase = file.path.stringOptoRemove Extension;
critical.generate({
base: 'app/',
src: file.path,
dest: 'css/' + fileBase + '.css'
});
}))
});
使用gulp-foreach 。
另外, glob-fs也會很有用,我包括下面編寫的示例代碼,該示例代碼處理流中的單個文件,然后使用新的文件名將其寫出。
var gulp = require('gulp');
var glob = require('glob-fs')({ gitignore: true });
var html2text = require('html-to-text');
var fs = require('fs');
var path = require('path');
gulp.task('default', function () {
glob.readdirStream('build/*.html')
.on('data', function (file) {
console.log(file.path);
html2text.fromFile(file.path, (err, text) => {
if (err) return console.error(err);
// strip off extension and parent directories
var filename = path.basename(file.path, '.html');
// I assume you want a.html text to be written to 'build/txt/a.txt'
fs.writeFileSync(path.join('build/txt', filename + '.txt'), text, 'utf8');
});
});
});
我正在使用gulp.src進行此工作。 唯一的問題是,在包含許多html文件的網站上需要花費3分鍾的時間才能完成,並且如果同時在計算機上執行其他操作,則很容易崩潰。 我實際上是通過嘗試找到一種更有效的方法來找到這篇文章的。
gulp.task('criticalCSS', ['compile-html', 'compile-styles'], function() {
return gulp.src(config.dest.root + '**/*.html')
.pipe(critical({
base: config.dest.root, // "app/" which is the root of my build folder
inline: true,
css: config.dest.css + styleBundleFilename, // "app/css/mainCssFilename"
dimensions: [{
width: 320,
height: 480
},{
width: 768,
height: 1024
},{
width: 1280,
height: 960
}],
ignore: ['font-face']
}))
.on('error', function(err) { log(err.message); })
.pipe(gulp.dest(config.dest.root));
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.