gulp-html-import,在html中引入外部html文件

栏目: Node.js · 发布时间: 6年前

内容简介:写于 2016.06.14项目地址:

写于 2016.06.14

项目地址:

gulp-html-import

曾经学习 PHP 的时候,深深觉得 include 语法非常好用,后接触了 ejs ,发现里面也有类似的语法,能够方便地引入公共html文件;在学习了 vuereact 等框架以后,“组件化思想”更是在我脑海根深蒂固,再也无法忍受每个页面重复大量代码的原始方法。但是,在最最普通的静态html开发过程中,我实在懒得用框架,只想用最基本的方式写几个静态页面出来,这时候才想起,没有 include 语法,每个页面的公共部分都要手动复制粘贴一次,实在不科学……

早上看了张鑫旭老师的文章 《JS一般般的网页重构可以使用Node.js做些什么》 ,深受启发,于是马上蹦起床尝试着把当中内容实现一遍,并尝试着搭配 gulp ,制作一个简单好用的插件,实现类似PHP include 语法能够引入静态html文件的功能。

因为喜欢less语法,所以使用了类似less的 @import 'xxx.less'; 作为引入方式。

下面直接粘贴项目readme的内容

gulp-html-import

A gulp plugin which can import .html files into .html files

Usage

First, install gulp-html-import as a devDependency:

npm install gulp-html-import --save-dev
复制代码

Then add it to the gulpfile.js :

var htmlImport = require('gulp-html-import');

gulp.task('import', function () {
    gulp.src('./demo/index.html')
        .pipe(gulpImport('./demo/components/'))
        .pipe(gulp.dest('dist')); 
})
复制代码

Example

Here is the files tree:

|
-- demo
|   |
|   -- components
|   |    |
|   |    -- header.html
|   |    |
|   |    -- footer.html
|   |
|   -- index.html
|
-- gulpfile.js
复制代码

Html files:

<!-- index.html -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Gulp-html-import Example</title>
</head>
<body>
    @import "header.html"
    <p>Hello World</p>
    @import "footer.html"
</body>
</html>
复制代码

In your index.html , you should use

@import "XXX.html"
复制代码

to import your components.

<!-- header.html -->

<h1>I am the header</h1>
复制代码
<!-- footer.html -->

<h1>I am the footer</h1>
复制代码

When you get into the root directory(where your gulpfile.js is) and type

gulp import
复制代码

you could see a html file in /dist like this:

<!-- /dist/index.html -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Gulp-html-import Example</title>
</head>
<body>
    <h1>I am the header</h1>
    <p>Hello World</p>
    <h1>I am the footer</h1>
</body>
</html>
复制代码

Everything is OK.


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

深入理解计算机系统

深入理解计算机系统

Randal E.Bryant、David O'Hallaron / 龚奕利、雷迎春 / 中国电力出版社 / 2004-5-1 / 85.00元

从程序员的视角,看计算机系统! 本书适用于那些想要写出更快、更可靠程序的程序员。通过掌握程序是如何映射到系统上,以及程序是如何执行的,读者能够更好的理解程序的行为为什么是这样的,以及效率低下是如何造成的。粗略来看,计算机系统包括处理器和存储器硬件、编译器、操作系统和网络互连环境。而通过程序员的视角,读者可以清晰地明白学习计算机系统的内部工作原理会对他们今后作为计算机科学研究者和工程师的工作有......一起来看看 《深入理解计算机系统》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

SHA 加密
SHA 加密

SHA 加密工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具