![](/img/trans.png)
[英]DOMParser appending <script> tags to <head>/<body> but not executing
[英]How do I add certain script tags inside <head> and <body> tags when using HtmlWebackPlugin
我正在使用 HtmlWebpackPlugin 用 javascript 生成 HTML 文件。
現在我想在<head>
和<body>
標簽的不同部分添加自定義腳本
例子:
我如何能,
<head>
標簽內添加<script> alert('in head tag') </script>
作為第一個孩子<body>
標簽內添加<script> alert('in body tag') </script>
作為第一個孩子這是我的 Webpack 配置中的片段
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
添加這兩個腳本標簽。
我猜您要問的是“如何在模板的兩個不同區域插入生成的包?” . 如果是這種情況,文檔中有一個部分提到了傳遞給模板文件的數據:
"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
看起來像
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 示例文件。 一個更簡單的示例,更具體到您的用例是:
<!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
因為你可以通過條目名稱訪問單個文件來代替。
多頁設置
對於多頁設置,您的 WP 配置可能如下所示
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>
我知道我遲到了,但這是我解決的方法。 我可能會幫助別人。
inject:false
禁用了資產的自動注入。new HtmlWebpackPlugin({
hash: true, // hash for cache bursting
template: "index.html", // source template
minify: true, // should html file be minified?
inject: false,
})
頭部的css
<% for (var css in htmlWebpackPlugin.files.css) { %>
<link href="<%= htmlWebpackPlugin.files.css[css] %>" rel="stylesheet">
<% } %>
js在體內
<% for (var js in htmlWebpackPlugin.files.js) { %>
<script src="<%= htmlWebpackPlugin.files.js[js] %>"></script>
<% } %>
您可以在這里進行任何類型的過濾/排序。
您可以在此處查看可用選項以及如何使用它們。
https://github.com/jaketrent/html-webpack-template/blob/master/index.ejs
您可以使用官方示例中所示的模板參數
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'
})
]
};
我遇到了同樣的問題,這就是我創建插件的原因。
HtmlWebpackInjector - 一個HtmlWebpackPlugin
助手,用於向頭部注入一些塊
它與HtmlWebpackPlugin
一起HtmlWebpackPlugin
,只需在塊名稱中添加_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()
]
}
這會自動將index
塊注入正文,將index_head
注入 html 文檔的頭部。 最終的 html 看起來像:
<!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>
我為你的問題感到抱歉,但我遇到了同樣的問題並被帶到了這里。
所以...我做了一個插件。 它似乎有效。
這(截至 2019-11-20)可能需要您卸載 html-webpack-plugin(當前穩定版),然后安裝 html-webpack-plugin@next。
npm install -D html-webpack-inject-string-plugin
我制作了一個插件來替換或插入htmlWebpackPlugin
輸出中的文本。 這意味着任何文本,任何地方,只要您搜索的內容在頁面上是唯一的(如</body>
標簽)。
html-webpack-plugin 為其編譯過程提供了鈎子。 我做了一個插件來搜索輸出字符串(在它被編譯之后)並在之前、之后或替換被搜索的字符串之前添加一個自定義字符串。
這就是為什么
我的問題是使用 Webpack 創建一個最小痛苦的 Wordpress 主題框架,它可以自動化更乏味的部分。 (我知道這是一口)
我需要為瀏覽器同步注入一個異步腳本標簽以與頁面連接。 但是(像您一樣)我找不到一種方法可以在沒有一點樣板的情況下將腳本普遍附加到頁面上。
所以我制作了一個插件,將我需要的字符串放入包含字符串</body>
每個文件中,因為這意味着它是一個整頁模板,我希望每個整頁模板在我更新源文件時自動刷新.
我發現的唯一問題是必須轉義已經轉義的反斜杠,因為輸出在瀏覽器中實際成為 html 之前通過編譯器運行。
所以請注意,您可能需要稍微捏造一下,毫無疑問,有人會遇到更多類似的問題。
但是我會冒昧地說這看起來像是您最初要求的解決方案。
https://github.com/smackjax/html-webpack-inject-string-plugin
如果這不是您要查找的內容或遇到問題,請告訴我!
也許你可以使用html-webpack-plugin/template-option和raw-loader
。
順便說一句,如果你得到[object Module]
結果,你需要使用default
屬性。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<%= require('!!raw-loader!./common/file1').default %>
<title>Document</title>
</head>
<body>
<%= require('!!raw-loader!./common/file2').default %>
</body>
</html>
對我來說,最簡單的方法是這樣做:
// webpüack.config.js
new HtmlWebpackPlugin({
template: 'index.html',
templateParameters: {
foo: process.env.BAR,
},
}),
<!-- index.html -->
<% if (foo) { %>
<script src="bar.min.js"></script>
<% } %>
奇跡般有效
使用此設置。
模板:根到您的 html 文件
new HtmlWebpackPlugin({
title: "chucknorris-app",
template: "./src/template.html",
}),
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.