我知道这已经有几个月了,但实际上我在寻找与此类似的答案时遇到了您的问题,并且我想出了一个解决方案,希望可以适用于您的项目。
看来您从 gulp-svgstore 的文档中获取了该代码。首先,您会注意到他们使用的注入标签用于注入 HTML:
<div class="visuallyhidden">
<!-- inject:svg --><!-- endinject -->
</div>
为了让它与 Pug 一起使用,您需要将标签更改为:
.visuallyhidden
//- inject:svg
//- endinject
这可能是你所需要的,但我想分享一些 gulp 任务,我曾经使用 <symbol> 元素将多个 SVG 组合成一个 SVG,然后我将这些元素注入到 .pug 模板中。
步骤
首先我创建了一个svgstore 任务,使用<symbol> 标签将多个 SVG 文件组合成一个 SVG。
gulp.task('svgstore', () => {
var target = gulp.src('app/includes/svg-defs.pug');
var source = gulp.src('app/svg/*.svg')
.pipe($.svgmin())
.pipe($.svgstore({inlineSvg: true}));
function fileContents(filePath, file) {
return file.contents.toString();
}
return target
.pipe($.inject(source, {transform: fileContents}))
.pipe(gulp.dest('app/includes'));
});
我的应用程序的结构如下:
app
|
+--includes
| |
| +--svg-defs.pug
| +--header.pug
+--svg
| |
| +--svg-1.svg
| +--svg-2.svg
+--images
+--styles
+--scripts
因此,svg 目录中的任何 SVG 文件都会合并为一个 SVG。
在svg-defs.pug 中我包含了注入标签:
.svg-defs-container.visuallyhidden
//- inject:svg
//- endinject
然后在我的 gulp serve 任务中,我必须在 svg 目录中包含任何 .svg 更改的监视。
gulp.task('serve', ['views', 'styles', 'scripts', 'fonts'], () => {
...
gulp.watch('app/svg/*.svg', ['svgstore']);
gulp.watch('app/data.json', ['views']);
gulp.watch('app/**/*.pug', ['views']);
gulp.watch('app/styles/**/*.scss', ['styles']);
gulp.watch('app/scripts/**/*.js', ['scripts']);
gulp.watch('app/fonts/**/*', ['fonts']);
gulp.watch('bower.json', ['wiredep', 'fonts']);
});
我还必须修改views 任务以运行svgstore,然后才能运行它的任何逻辑。这是因为我们想在 gulp 将我们的 pug 编译成 HTML 之前将单个 SVG 注入到我们的模板中。
gulp.task('views', ['svgstore'], () => {
return gulp.src('app/*.pug')
.pipe($.plumber())
.pipe($.pug({pretty: true}))
.pipe(gulp.dest('.tmp'))
.pipe(reload({stream: true}));
});
最后,我刚刚在我的index.pug 文件中添加了一个简单的include:
包括 ./includes/mixin-interior.pug
doctype html
html.no-js(lang='')
include ./includes/head.pug
body
include ./includes/browser-support.pug
include ./includes/analytics.pug
include ./includes/svg-defs.pug
...
我使用 Yeoman 的 generator-webapp 生成我的项目和 gulpfile.js。我必须进行一些定制才能使其与 Pug 一起使用,但如果事情没有意义,请查看完整的 gulpfile。