16

For example, I have a main entry html file:

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

And I have a partial html

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

I hope that I can use webpack to generate a final html like below:

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

Is it possible to do this with webpack plugin/loaders?

Chris
  • 513
  • 2
  • 7
  • 12

2 Answers2

6

There is a couple of loaders to achieve this: https://webpack.github.io/docs/list-of-loaders.html#templating


For example:

html-loader

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

ejs-html-loader

<% include some/file %>
Bob Sponge
  • 4,708
  • 1
  • 23
  • 25
  • 2
    I have same probleme and when i use
    ${require('./partials/gallery.html')}
    the require isn't interpretate
    – Lionel B Dec 19 '17 at 14:33
  • 2
    I can't get this to work, can you give a working example? – Ruby Jan 23 '18 at 07:38
  • 1
    @VishalSharma, did you find out how to do it? – Alex Mar 10 '18 at 21:12
  • @alex ended up writing my own script. – Vishal Sharma Mar 10 '18 at 21:49
  • yes for me also not working, i installed "npm i -D html-loader" and then i write this - "
    ${require("html-loader!./file.html")}
    " - code in index.html inside the body. and also i included the module { test: /\.html$/, use: [ 'file-loader?name=[./html][name].[ext]!extract-loader!html-loader' ] }
    –  May 10 '18 at 13:27
  • @VishalSharma how did you do that? –  May 10 '18 at 13:28
  • To make it work you need to enable `interpolate` Here is sample code `{ test: /\.html$/, use: [{ loader: 'html-loader', options: { interpolate:true, minimize: true /*removeComments: false, collapseWhitespace: true*/ } }], }` – brk May 20 '18 at 09:36
3

You can use this plugin github.com/bazilio91/ejs-compiled-loader:

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

Change your .html files in .ejs and your HtmlWebpackPlugin to point to the right .ejs template:

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

You can import partials, variables, and assets in .ejs files:

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>

A note, when you include a partial the path must be relative to the root of your project.

I answered the same question here stackoverflow.com/a/48750048/7448956.

pldg
  • 2,427
  • 3
  • 22
  • 37