我最近问为什么self-closing elements do not work在 Aurelia 的模板系统中;这是因为自动关闭元素是无效的 html。
然而,今天我又犯了同样的错误(这次是小部件),我一直在摸不着头脑,为什么内容丢失了。
问题:是否有办法在 gulp 任务中清理 Aurelia 模板 html?
我试过使用:
gulp-htmlhint
:无法在自闭元素上出错gulp-htmllint
:无法配置;使用默认设置,它会因错误而爆炸。gulp-html5-lint
:看起来不可配置,它讨厌 aurelia 的属性。
最佳答案
我们可以使用 parse5 解决查找和报告自闭合元素的问题。 .它有一个 SAXParser 类,应该是相当健壮的(parse5 符合 html5 标准)。解析器在找到开始标签时引发一个事件,该事件包含一个 bool 值,表示找到的标签是否自行关闭。
var parser = new SAXParser();
parser.on("startTag", (name, attrs, selfClosing)=>{
if(selfClosing){
//check if name is void, if not report error
}
});
parser.push(html);
为了利用此功能,我建立了一个项目,可用于使用上述方法帮助清理 html。开发的 lint 工具能够运行一系列规则,收集任何错误并将它们作为 Promise 返回。然后可以将此报告给用户。
Vanilla Html/模板
template-lint构成工具集的基础。它由 Linter 和一些基本规则组成:
- SelfClose - 确保非 void 元素不会自关闭
- 解析器 - 返回解析期间捕获的未闭合或不匹配元素的错误
gulp-template-lint是 template-lint 的 gulp 包装器,可以像这样使用:
var gulp = require('gulp');
var linter = require('gulp-template-lint');
gulp.task('build-html', function () {
return gulp.src(['source/**/*.html'])
.pipe(linter())
.pipe(gulp.dest('output'));
});
例子
给定以下 html:
<template>
<custom-element/>
<svg>
<rect/>
</svg>
<div>
<div>
</div>
</template>
产生:
注:自闭<rect/>
不会产生错误。 svg 元素包含 xml,规则可以根据范围进行区分。
Aurelia 模板
我最初做了 aurelia-template-lint ,但决定将可重用(aurelia 之外)组件拆分为 template-lint .虽然两者目前是分开的,但我将拥有 aurelia-template-lint延伸至 template-lint在适当的时候。目前有一些概念验证规则:
- SelfClose - 确保非 void 元素不会自关闭
- 解析器 - 返回解析期间捕获的未闭合或不匹配元素的错误
- 模板 - 确保根是一个模板元素,并且存在的模板元素不超过一个
- RouterView - 不允许路由器 View 元素包含内容元素
- 要求 - 确保要求元素具有“来自”属性
可以通过以下方式安装 gulp 包装器:
npm install gulp-aurelia-template-lint
并在 gulp 构建中使用:
var linter = require('gulp-aurelia-template-lint');
gulp.task('lint-template-html', function () {
return gulp.src('**/*.html')
.pipe(linter())
.pipe(gulp.dest('output'));
});
这将使用默认的规则集。
例子
使用以下格式错误的 aurelia 模板进行简单测试:
<link/>
<template bindable="items">
<require from="foo"/>
<require frm="foo"/>
<br/>
<div></div>
<router-view>
<div/>
</router-view>
</template>
<template>
</template>
输出:
改进
有很多需要改进的地方;例如,有几种方法可以在不使用 <template>
的情况下定义普通模板标签。 Aurelia 还引入了很多可以清理的特定属性。
关于html - Aurelia:完整性检查模板 html?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37322985/