如何在 <head> 中添加某些脚本标签?和<身体>使用 HtmlWebackPlugin 时的标签 [英] How do I add certain script tags inside <head> and <body> tags when using HtmlWebackPlugin
问题描述
我正在使用 HtmlWebpackPlugin 用 javascript 生成 HTML 文件.
I'm using HtmlWebpackPlugin to generate HTML files with javascript.
现在我想在 和
标签的不同部分添加自定义脚本
Now I would like to add custom script at different parts of <head>
and <body>
tags
示例:
我该怎么办,
- 添加<代码><脚本>alert('in head tag') 里面
标签作为第一个孩子
- 添加<代码><脚本>alert('in body tag') 里面
标签作为第一个孩子
- Add
<script> alert('in head tag') </script>
inside the<head>
tag as the first child - Add
<script> alert('in body tag') </script>
inside the<body>
tag as the first child
这是我的 Webpack 配置中的代码片段
Here is the snippet in my Webpack config
new HtmlWebpackPlugin({
hash: true,
chunks: ["app"],
filename: path.resolve(__dirname, "./public/pages/app.html"),
title: "Title of webpage",
template: path.resolve(__dirname, "./src/pages/app.page.html"),
minify: {
collapseWhitespace: true
}
})
推荐答案
你的问题有点令人困惑.这意味着您要向模板添加静态脚本标签.如果是这种情况,您只需进入 src/pages/app.page.html
文件并在 head
和 body<中添加这两个脚本标记/代码>.
Your question is a bit confusing. It implies you want to add static script tags to your template. If that's the case you just need to go into your src/pages/app.page.html
file and add those two script tags in the head
and body
.
我猜您要问的是如何在模板的两个不同区域插入生成的包?".如果是这种情况,文档中有一个 部分提到了传递给模板文件的数据:
What I'm guessing that you're asking is "How do I insert generated bundles in two different areas of my template?". If that's the case there's a section in the docs that mentions what data is passed to the template file:
"htmlWebpackPlugin": {
"files": {
"css": [ "main.css" ],
"js": [ "assets/head_bundle.js", "assets/main_bundle.js"],
"chunks": {
"head": {
"entry": "assets/head_bundle.js",
"css": [ "main.css" ]
},
"main": {
"entry": "assets/main_bundle.js",
"css": []
},
}
}
}
所以如果你的 entry
看起来像
So if your entry
looked like
entry: {
head: './src/file1.js',
body: './src/file2.js',
}
并且您的插件设置为
new HtmlWebpackPlugin({
template: './src/pages/app.page.ejs' // note the .ejs extension
})
然后 app.page.ejs
应该能够访问插件中的数据,您可以将这些条目放在您想要的任何位置.他们的 repo 中有一个很大的 ejs 示例文件.一个更简单的例子,更具体到你的用例是:
then app.page.ejs
should be able to access the data from the plugin and you can place those entries where ever you'd like. There's a large ejs example file in their repo. A simpler example, and one more specific to your use case would be:
<!DOCTYPE html>
<head>
<% if(htmlWebpackPlugin.files.chunks.head) { %>
<script src="<%= htmlWebpackPlugin.files.chunks.head.entry %>"></script>
<% } %>
</head>
<body>
<% if(htmlWebpackPlugin.files.chunks.body) { %>
<script src="<%= htmlWebpackPlugin.files.chunks.body.entry %>"></script>
<% } %>
</body>
</html>
请注意,我使用的不是 files.js
而是 files.chunks
,因为您可以通过条目名称访问单个文件.
Note that I'm not using files.js
but rather files.chunks
since you can access single files by entry name instead.
多页设置
对于多页设置,您的 WP 配置可能如下所示
For a multi-page set-up your WP config could look like
const pages = [
'home',
'about',
];
const conf = {
entry: {
// other entries here
}
output: {
path: `${ __dirname }/dist`,
filename: 'scripts/[name].js'
},
plugins: [
// other plugins here
]
};
// dynamically add entries and `HtmlWebpackPlugin`'s for every page
pages.forEach((page) => {
conf.entry[page] = `./src/pages/${ page }.js`;
conf.plugins.push(new HtmlWebpackPlugin({
chunks: [page],
// named per-page output
filename: `${ __dirname }/dist/pages/${ page }.html`,
googleAnalytics: { /* your props */ },
// shared head scripts
headScripts: [
{
src: 'scripts/jQuery.js'
},
{
content: `
console.log('hello world');
alert('huzah!');
`
}
],
// per-page html content
pageContent: fs.readFileSync(`./src/pages/${ page }.html`, 'utf8'),
// one template for all pages
template: './src/pages/shell.ejs',
}));
});
module.exports = conf;
模板看起来像
<!DOCTYPE html>
<head>
<%
for (var i=0; i<htmlWebpackPlugin.options.headScripts.length; i++) {
var script = htmlWebpackPlugin.options.headScripts[i];
%>
<script
<% if(script.src){ %>src="<%= script.src %>"<% } %>
>
<% if(script.content){ %><%= script.content %><% } %>
</script>
<% } %>
</head>
<body>
<% if(htmlWebpackPlugin.options.pageContent) { %>
<%= htmlWebpackPlugin.options.pageContent %>
<% } %>
<% for (var chunk in htmlWebpackPlugin.files.chunks) { %>
<script src="<%= htmlWebpackPlugin.files.chunks[chunk].entry %>"></script>
<% } %>
<% if (htmlWebpackPlugin.options.googleAnalytics) { %>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
<% if (htmlWebpackPlugin.options.googleAnalytics.trackingId) { %>
ga('create', '<%= htmlWebpackPlugin.options.googleAnalytics.trackingId%>', 'auto');
<% } else { throw new Error("html-webpack-template requires googleAnalytics.trackingId config"); }%>
<% if (htmlWebpackPlugin.options.googleAnalytics.pageViewOnLoad) { %>
ga('send', 'pageview');
<% } %>
</script>
<% } %>
</body>
</html>
这篇关于如何在 <head> 中添加某些脚本标签?和<身体>使用 HtmlWebackPlugin 时的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!