我有一个在 gulp 中使用工作流的前端项目。
插件:
gulpfile.js:
var
gulp = require('gulp'),
...
var path = {
app : { // src
html : 'app/*.html',
js : 'app/js/*.js',
svg : 'app/**/*.svg',
},
dist : { // dist
html : 'dist/',
js : 'dist/js/',
},
watch : { // watcher
html : 'app/**/*.html',
svg : 'app/**/*.svg',
js : 'app/js/**/*.js',
}
};
// server
var config = {
server : {
'baseDir' : './dist'
},
host : 'localhost',
port : 9000,
tunel : true,
};
// HTML
gulp.task('html', ['svg'], function(){
gulp.src(path.app.html)
.pipe(rigger())
.pipe(useref())
.pipe(gulpif('*.js', uglify()))
.pipe(gulpif('*.css', minifyCss()))
.pipe(inject(svgContent, { transform: fileContents }))
.pipe(gulp.dest(path.dist.html))
.pipe(reload({stream : true}));
});
// JS
gulp.task('js', function(){
gulp.src(path.app.js)
.pipe(gulp.dest(path.dist.js))
.pipe(reload({stream : true}));
});
// SVG
function fileContents (filePath, file) {
return file.contents.toString();}
var svgContent = gulp.src(path.app.svg)
.pipe(svgmin())
.pipe(svgstore({ inlineSvg: true }))
.pipe(reload({stream : true}));
gulp.task('svg', function () {
var svgs = svgContent;
});
// watcher
gulp.task('watch', function () {
watch([path.watch.html], function(event, cb){
gulp.start('html');
});
watch([path.watch.html], function(event, cb){
gulp.start('svg');
});
watch([path.watch.js], function(event, cb){
gulp.start('js');
});
});
// start server
gulp.task('webserver', function(){
browserSync(config);
});
// Cleaning
gulp.task('clean', function(cb){
clean(path.clean, cb);
});
// Default task
gulp.task('default', [
'html',
'svg',
'js',
'webserver',
'watch'
]);
html:
...
<div style="height: 0; width: 0; position: absolute; visibility: hidden">
<!-- inject:svg --><!-- endinject -->
</div>
...
<!-- build:js js/vendor.js -->
<script src="libs/jquery/jquery-2.1.3.min.js"></script>
...
<!-- endbuild -->
在 html 文件发生变化之前,一切正常。任何更改都会导致编译的内联 svg 文件消失在 html 文件中(在注入(inject)中)。
我试了一下代码:
gulpfile.js:
// html
gulp.task('html', function(){
gulp.src(path.app.html)
.pipe(useref())
.pipe(gulpif('*.js', uglify()))
.pipe(gulpif('*.css', minifyCss()))
.pipe(gulp.dest(path.dist.html))
.pipe(reload({stream : true}));
});
// SVG
gulp.task('svg', function () {
var svgs = gulp.src(path.app.svg)
.pipe(svgstore({ inlineSvg: true }));
function fileContents (filePath, file) {
return file.contents.toString();
}
return gulp.src(path.app.html)
.pipe(inject(svgs, { transform: fileContents }))
.pipe(gulp.dest(path.dist.other));
});
一切正常,Web 服务器重新启动并清除任何 html
文件的更改并保存 svg
sprite,但是任务 useref()
停止工作。
<!-- build:js js/vendor.js -->
<script src="libs/jquery/jquery-3.2.1.min.js"></script>
<script src="libs/animate/wow.min.js"></script>
....
<!-- endbuild -->
构建 vendor.js 文件,但不写入 dist/index.html
。生成后应该是:
<script src="js/vendor.js"></script>
问题: 是否可以配置 gulpfile.js,这样您就可以更改 html 文件,而无需在控制台中重新启动整个程序集,也不会丢失 html 文件中生成的 svg sprite?
最佳答案
关于javascript - 更改 html 文档时保存注入(inject) svg 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54002844/