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

项目地点:

gulp-html-import

曾进修PHP的时刻,深深以为include语法异常好用,后打仗了ejs,发明内里也有相似的语法,能够方便地引入大众html文件;在进修了vuereact等框架今后,“组件化头脑”更是在我脑海根深蒂固,再也无法忍受每一个页面反复大批代码的原始要领。然则,在最最一般的静态html开辟过程当中,我着实懒得用框架,只想用最基本的体式格局写几个静态页面出来,这时刻才想起,没有include语法,每一个页面的大众部份都要手动复制粘贴一次,着实不科学……

早上看了张鑫旭先生的文章《JS一般般的网页重构能够运用Node.js做些什么》,深受启示,因而立时蹦起床尝试着把当中内容完成一遍,并尝试着搭配gulp,制造一个简朴好用的插件,完成相似PHPinclude语法能够引入静态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.

API

htmlImport(string)

string

Type: String

The url of your components

MIT

Copyright © 2016 Jrain Lau

    原文作者:jrainlau
    原文地址: https://segmentfault.com/a/1190000005719119
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞