有没有办法将html部分包含在另一个使用webpack的部分中?我正在使用html-加载程序来执行此操作:
index.html
<%= require('html-loader!./partials/_header.html') %>但是,当我试图在_header.html中包含另一个部分时,它无法呈现它。
这是行不通的:
_header.html
<%= require('html-loader!./partials/_nav.html') %>发布于 2018-05-09 19:43:31
我结合了一点,我找到了一个解决方案。
index.html
<%= require('html-loader?root=.&minimize=true&interpolate!./partials/_header.html') %>然后在_header.html
${require('html-loader?root=.!../partials/_nav.html')}发布于 2018-04-27 14:17:44
使用html-loader和interpolate选项。
https://github.com/webpack-contrib/html-loader#interpolation
{ test: /\.(html)$/,
include: path.join(__dirname, 'src/views'),
use: {
loader: 'html-loader',
options: {
interpolate: true
}
}
}然后,在html页面中,可以导入partials、html和javascript变量。
<!-- Importing top <head> section -->
${require('./partials/top.html')}
<title>Home</title>
</head>
<body>
<!-- Importing navbar -->
${require('./partials/nav.html')}
<!-- Importing variable from javascript file -->
<h1>${require('../js/html-variables.js').hello}</h1>
<!-- Importing footer -->
${require('./partials/footer.html')}
</body>
</html>html-variables.js看起来是这样的:
const hello = 'Hello!';
const bye = 'Bye!';
export {hello, bye}您还可以使用${require('path/to/your/partial.html')以相同的方式在另一个部分中包含部分。
唯一的缺点是您无法从HtmlWebpackPlugin中导入其他变量,比如这个<%= htmlWebpackPlugin.options.title %> (至少我无法找到导入它们的方法),只需在html中写入标题,或者在需要时使用单独的javascript文件来处理变量。
https://stackoverflow.com/questions/49168671
复制相似问题