如何连接 js/css 文件并使用 gulp 替换 html?
How to concat js/css files and replace in html using gulp?
这里有很多问答如何在模板中进行资源拼接或替换。使用grunt-concat
合并文件,使用gulp-html-replace
替换模板。而且我不明白如何将它们相互联系起来。
因此给定模板,friends.tpl
具有特殊的 css 文件集:
!DOCTYPE html>
<html>
<head>
<!-- build:css friends.min.css -->
<link rel="stylesheet" href="css/component1/style.css">
...
<link rel="stylesheet" href="css/componentN/style.css">
<!-- /build -->
</head>
<body/>
想要的结果
!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/friends.min.css">
</head>
<body/>
并使用上面的串联文件创建了 friends.min.css 文件。
如何实现 - 基于模板数据的连接
使用 gulp-htmlbuild,它会做你想要的。
gulp.task('build', function () {
gulp.src(['./index.html'])
.pipe(htmlbuild({
// build js with preprocessor
js: htmlbuild.preprocess.js(function (block) {
// read paths from the [block] stream and build them
// ...
// then write the build result path to it
block.write('buildresult.js');
block.end();
})
}))
.pipe(gulp.dest('./build'));
});
gulp 构建需要 index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<!-- htmlbuild:js -->
<script src="js/script1.js"></script>
<script src="js/script2.js"></script>
<!-- endbuild -->
</body>
</html>
并把它变成:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script src="buildresult.js"></script>
</body>
</html>
这里有很多问答如何在模板中进行资源拼接或替换。使用grunt-concat
合并文件,使用gulp-html-replace
替换模板。而且我不明白如何将它们相互联系起来。
因此给定模板,friends.tpl
具有特殊的 css 文件集:
!DOCTYPE html>
<html>
<head>
<!-- build:css friends.min.css -->
<link rel="stylesheet" href="css/component1/style.css">
...
<link rel="stylesheet" href="css/componentN/style.css">
<!-- /build -->
</head>
<body/>
想要的结果
!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/friends.min.css">
</head>
<body/>
并使用上面的串联文件创建了 friends.min.css 文件。
如何实现 - 基于模板数据的连接
使用 gulp-htmlbuild,它会做你想要的。
gulp.task('build', function () {
gulp.src(['./index.html'])
.pipe(htmlbuild({
// build js with preprocessor
js: htmlbuild.preprocess.js(function (block) {
// read paths from the [block] stream and build them
// ...
// then write the build result path to it
block.write('buildresult.js');
block.end();
})
}))
.pipe(gulp.dest('./build'));
});
gulp 构建需要 index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<!-- htmlbuild:js -->
<script src="js/script1.js"></script>
<script src="js/script2.js"></script>
<!-- endbuild -->
</body>
</html>
并把它变成:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script src="buildresult.js"></script>
</body>
</html>