是否可以使用Vite (vanilla)包括共享HTML的片段?我正在寻找一种不用通过JS注入就可以预先录制HTML的方法。
类似于:
<html>
<head>
{ include 'meta-tags' }
</head>
<body>
{ include 'nav' }
<h1>Hello World</h1>
<body>
</html>发布于 2022-01-31 00:04:29
vite-plugin-handlebars是我一直在寻找的解决方案。使用此包设置部分非常容易:
设置:
// vite.config.js
import { resolve } from 'path';
import handlebars from 'vite-plugin-handlebars';
export default {
plugins: [
handlebars({
partialDirectory: resolve(__dirname, 'partials'),
}),
],
};要包含部分内容的文件:
<!-- index.html -->
{{> header }}
<h1>The Main Page</h1>呈现的产出:
<header><a href="/">My Website</a></header>
<h1>The Main Page</h1>发布于 2022-01-29 06:15:42
您可以使用在vite-plugin-html中启用EJS模板的index.html
// vite.config.js
import { defineConfig } from 'vite'
import { createHtmlPlugin } from 'vite-plugin-html'
export default defineConfig({
plugins: [
createHtmlPlugin({
entry: 'main.js',
/**
* Data that needs to be injected into the index.html ejs template
*/
inject: {
data: {
metaTags: `<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />`,
nav: `<nav>
<a href="https://google.com">Google</a> |
<a href="https://apple.com">Apple</a>
</nav>`,
},
},
}),
],
})<!-- index.html -->
<html>
<head>
<%- metaTags %>
</head>
<body>
<%- nav %>
<h1>Hello World</h1>
<body>
</html>https://stackoverflow.com/questions/70818545
复制相似问题