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
Example:
How do I,
- 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
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
}
})
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": []
},
}
}
}
So if your entry
looked like
entry: {
head: './src/file1.js',
body: './src/file2.js',
}
and your plugin was set to
new HtmlWebpackPlugin({
template: './src/pages/app.page.ejs' // note the .ejs extension
})
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>
Note that I'm not using files.js
but rather files.chunks
since you can access single files by entry name instead.
Multi-Page Set-Up
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;
The template would look something like
<!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>
You can use template parameters like shown in the official example
var path = require('path');
var HtmlWebpackPlugin = require('../..');
var webpackMajorVersion = require('webpack/package.json').version.split('.')[0];
module.exports = {
context: __dirname,
entry: './example.js',
output: {
path: path.join(__dirname, 'dist/webpack-' + webpackMajorVersion),
publicPath: '',
filename: 'bundle.js'
},
plugins: [
new HtmlWebpackPlugin({
templateParameters: {
'foo': 'bar'
},
template: 'index.ejs'
})
]
};
I came across the same problem that's why I created a plugin.
HtmlWebpackInjector - A
HtmlWebpackPlugin
helper to inject some chunks to headIt works with
HtmlWebpackPlugin
and by just adding_head
in the name of chunk, it automaticlly injects the chunk in the head.
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackInjector = require('html-webpack-injector');
module.exports = {
entry: {
index: "./index.ts",
index_head: "./index.css" // add "_head" at the end to inject in head.
},
output: {
path: "./dist",
filename: "[name].bundle.js"
},
plugins: [
new HtmlWebpackPlugin({
template: "./index.html",
filename: "./dist/index.html",
chunks: ["index", "index_head"]
}),
new HtmlWebpackInjector()
]
}
This automatically injects index
chunk to the body and index_head
to the head of the html document. Final html looks like:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Archit's App</title>
<script type="text/javascript" src="index_head.bundle.js"></script> <--injected in head
</head>
</head>
<body>
<script src="index_bundle.js"></script> <--injected in body
</body>
</html>
来源:https://stackoverflow.com/questions/51285711/how-do-i-add-certain-script-tags-inside-head-and-body-tags-when-using-htmlwe