Can webpack connect the html module directly in html without introducing a template engine?

recently trying to use webpack to build a project, ask which library can implement the function of referencing the html module in the line of the html file?

at present, all I know is that the webpack template engine can do this kind of stitching. Can I write it directly into html?

Thank you!

for example:

a.html

<div class="blue-box">blue</div>

main.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Center</title>
</head>
<body>
    // a.html
    <div class="red-box">red</div>
</body>
</html>

result:

main.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Center</title>
</head>
<body>
    <div class="blue-box">blue</div>
    <div class="red-box">red</div>
</body>
</html>
Mar.09,2021

Yes, read and write the file directly with node, and write the contents of a.html into main.html. Even webpack does not need


you can use webpack's html-webpack-plugin to cooperate with the template engine to assemble and generate html files. Specifically, see these two articles: " webpack multi-page application architecture series (12): using webpack to generate HTML ordinary web pages & page template " "webpack multi-page application architecture series (13): build a simple template layout system"


html-loader


landlord, How did you solve this problem? Ask for advice


you can use raw-loader

template html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    ${require('raw-loader!./a.tpl.html')}
    ${require('raw-loader!./b.tpl.html')}
    <div><h1>this is "index.html" own content</h1></div>
</body>
</html>

webpack configuration

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './web/src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name]-[hash].js'
  },
  plugins: [
    new HtmlWebpackPlugin({
        title: 'inline_html',
        minify: false,
      loader: "raw-loader",
      template: 'web/src/index.html'
    })
  ]
};

generated code html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <div><h1>this is "a.tpl.html" file content</h1></div>
    <div><h1>this is "b.tpl.html" file content</h1></div>
    <div><h1>this is "index.html" own content</h1></div>
    <script type="text/javascript" src="main-b173a8766c84b7b7e5b1.js"></script>
</body>
</html>

directory structure

Menu