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

寫於 2016.06.14css

項目地址:html

gulp-html-importvue

曾經學習PHP的時候,深深以爲include語法很是好用,後接觸了ejs,發現裏面也有相似的語法,可以方便地引入公共html文件;在學習了vuereact等框架之後,「組件化思想」更是在我腦海根深蒂固,再也沒法忍受每一個頁面重複大量代碼的原始方法。可是,在最最普通的靜態html開發過程當中,我實在懶得用框架,只想用最基本的方式寫幾個靜態頁面出來,這時候纔想起,沒有include語法,每一個頁面的公共部分都要手動複製粘貼一次,實在不科學……node

早上看了張鑫旭老師的文章《JS通常般的網頁重構可使用Node.js作些什麼》,深受啓發,因而立刻蹦起牀嘗試着把當中內容實現一遍,並嘗試着搭配gulp,製做一個簡單好用的插件,實現相似PHPinclude語法可以引入靜態html文件的功能。react

由於喜歡less語法,因此使用了相似less的@import 'xxx.less';做爲引入方式。git

下面直接粘貼項目readme的內容github


gulp-html-import

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

Usage

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

npm install gulp-html-import --save-dev
複製代碼

Then add it to the gulpfile.js:bash

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

相關文章
相關標籤/搜索