如何使用webpack来连接html片段?

时间:2016-03-25 08:19:51

标签: webpack

例如,我有一个主条目html文件:

<div>
   <!-- I'd like to include a html partial here -->
</div>

我有一个部分HTML

<span>I'm a partial html piece</span>

我希望我可以使用webpack生成如下的最终html:

<div>
  <span>I'm a partial html piece</span>
</div>

是否可以使用webpack插件/加载器执行此操作?

2 个答案:

答案 0 :(得分:6)

有几个加载器可以达到这个目的: https://webpack.github.io/docs/list-of-loaders.html#templating

例如:

html-loader

<div>${require('./partials/gallery.html')}</div>

ejs-html-loader

<% include some/file %>

答案 1 :(得分:2)

您可以使用此插件github.com/bazilio91/ejs-compiled-loader

{ test: /\.ejs$/, use: 'ejs-compiled-loader' }

.html.ejs中的HtmlWebpackPlugin文件更改为指向右侧.ejs模板:

new HtmlWebpackPlugin({
    template: 'src/views/index.ejs',
    filename: 'index.html',
    title: 'Home',
    chunks: ['index']
})

您可以在.ejs个文件中导入部分,变量和资源:

src/views/partials/head.ejs

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8"/>
  <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <title><%= htmlWebpackPlugin.options.title %></title>
</head>

src/js/ejs_variables.js

const hello = 'Hello!';
const bye = 'Bye!';

export {hello, bye}

src/views/index.ejs

<% include src/views/partials/head.ejs %>
<body>    
  <h2><%= require("../js/ejs_variables.js").hello %></h2>

  <img src=<%= require("../../assets/sample_image.jpg") %> />

  <h2><%= require("../js/ejs_variables.js").bye %></h2>
</body>

注意,当您包含部分路径时,路径必须相对于项目的根目录。

我在这里回答了同样的问题stackoverflow.com/a/48750048/7448956