webpack可以不引入模板引擎,直接在html里内连html模块吗?

最近在尝试使用webpack构建工程,求问哪个库可以实现html文件行内引用html模块的功能?

目前我只知道webpack配合模板引擎可以进行这种拼接,可以直接写到html里吗?

谢谢!

例如:

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>

结果:

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>
阅读 13.5k
5 个回答

可以,直接用node读写文件,将a.html的内容写入main.html里面,连webpack都可以不要

新手上路,请多包涵

可以使用raw-loader

模板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配置

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'
    })
  ]
};

生成的代码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>

目录结构

图片描述

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏