使用 javascript gulp 工具
它会是这样的:
@@include('./header.html')
<!-- Content -->
<section>
<h1>Hello world</h1>
</section>
@@include('./footer.html')
选择包含重复块的最佳方法之一是使用 Gulp.js 和一些包。 gulp 是一个流行的 JavaScript 工具包,用于自动化和增强您的工作流程。
为了使用它,首先使用 yarn 或 npm 在你的项目中安装 gulp :
yarn init
安装 gulp-file-include 插件:
yarn add gulp gulp-file-include -D
创建 gulpfile 以便能够使用 Gulp 创建任务
在 Linux 中:
touch gulpfile.js
如果您使用的是 Windows,请改用此命令:
type "gulpfile.js"
在 gulpfile.js 中导入 gulp 和 gulp-file-include。您还将创建一个变量路径来定义源路径和目标路径(构建后静态 html 文件所在的位置):
const gulp = require('gulp');
const fileinclude = require('gulp-file-include');
const paths = {
scripts: {
src: './',
dest: './build/'
}
};
在 gulpfile.js 文件中,创建一个任务函数,负责包含 html 文件并返回静态文件:
async function includeHTML(){
return gulp.src([
'*.html',
'!header.html', // ignore
'!footer.html' // ignore
])
.pipe(fileinclude({
prefix: '@@',
basepath: '@file'
}))
.pipe(gulp.dest(paths.scripts.dest));
}
现在将功能设置为默认值:
exports.default = includeHTML;
将包含标签添加到 index.html:
@@include('./header.html')
<!-- Content -->
<section>
<h1>Hello world</h1>
</section>
@@include('./footer.html')
运行 gulp 命令:
yarn gulp
build 文件夹将在里面创建 index.html 文件
完成:)