简体   繁体   English

如何在里面添加某些脚本标签<head>和<body>使用 HtmlWebackPlugin 时的标签

[英]How do I add certain script tags inside <head> and <body> tags when using HtmlWebackPlugin

I'm using HtmlWebpackPlugin to generate HTML files with javascript.我正在使用 HtmlWebpackPlugin 用 javascript 生成 HTML 文件。

Now I would like to add custom script at different parts of <head> and <body> tags现在我想在<head><body>标签的不同部分添加自定义脚本

Example:例子:

How do I,我如何能,

  1. Add <script> alert('in head tag') </script> inside the <head> tag as the first child<head>标签内添加<script> alert('in head tag') </script>作为第一个孩子
  2. Add <script> alert('in body tag') </script> inside the <body> tag as the first child<body>标签内添加<script> alert('in body tag') </script>作为第一个孩子

Here is the snippet in my Webpack config这是我的 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
        }
    })

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 .如果是这种情况,您只需进入src/pages/app.page.html文件并在headbody添加这两个脚本标签。

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看起来像

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.然后app.page.ejs应该能够访问插件中的数据,您可以将这些条目放在您想要的任何位置。 There's a large ejs example file in their repo.他们的 repo 中有一个很大的ejs 示例文件 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.请注意,我没有使用files.js而是files.chunks因为你可以通过条目名称访问单个文件来代替。


Multi-Page Set-Up多页设置

For a multi-page set-up your WP config could look like对于多页设置,您的 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;

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>

I know I am late but here is how I resolved it.我知道我迟到了,但这是我解决的方法。 I might help someone else.我可能会帮助别人。

  1. I disabled auto inject of assets with inject:false .我使用inject:false禁用了资产的自动注入。
new HtmlWebpackPlugin({
  hash: true, // hash for cache bursting
  template: "index.html", // source template
  minify: true, // should html file be minified?
  inject: false,
}) 
  1. Manually rendered assets in the template file.模板文件中手动渲染的资产。

css in the head头部的css

<% for (var css in htmlWebpackPlugin.files.css) { %>
<link href="<%= htmlWebpackPlugin.files.css[css] %>" rel="stylesheet">
<% } %>

js in the body js在体内

<% for (var js in htmlWebpackPlugin.files.js) { %>
<script src="<%= htmlWebpackPlugin.files.js[js] %>"></script>
<% } %>

You can literally do any kind of filtering/sorting here.您可以在这里进行任何类型的过滤/排序。

You can view the available options and how to use them here.您可以在此处查看可用选项以及如何使用它们。

https://github.com/jaketrent/html-webpack-template/blob/master/index.ejs https://github.com/jaketrent/html-webpack-template/blob/master/index.ejs

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 head HtmlWebpackInjector - 一个HtmlWebpackPlugin助手,用于向头部注入一些块

  • It works with HtmlWebpackPlugin and by just adding _head in the name of chunk, it automaticlly injects the chunk in the head.它与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()
  ]
}

This automatically injects index chunk to the body and index_head to the head of the html document.这会自动将index块注入正文,将index_head注入 html 文档的头部。 Final html looks like:最终的 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>

I apologize for necro-ing your question, but I had the same problem and was brought here.我为你的问题感到抱歉,但我遇到了同样的问题并被带到了这里。

So...I made a plugin.所以...我做了一个插件。 And it seems to work.它似乎有效。

This(as of 2019-11-20) might require you to uninstall html-webpack-plugin(current stable), then install html-webpack-plugin@next.这(截至 2019-11-20)可能需要您卸载 html-webpack-plugin(当前稳定版),然后安装 html-webpack-plugin@next。

TL;DR:特尔;博士:

I made a plugin that replaces or inserts text in the htmlWebpackPlugin output.我制作了一个插件来替换或插入htmlWebpackPlugin输出中的文本。 That means any text, anywhere, as long as what you're searching for is unique on the page(like a </body> tag).这意味着任何文本,任何地方,只要您搜索的内容在页面上是唯一的(如</body>标签)。

Here's how就是这样

html-webpack-plugin gives hooks for it's compilation process. html-webpack-plugin 为其编译过程提供了钩子。 I made a plugin that searches the output string(after it's been compiled) and adds a custom string either before, after, or replacing the one that was searched.我做了一个插件来搜索输出字符串(在它被编译之后)并在之前、之后或替换被搜索的字符串之前添加一个自定义字符串。

Here's why这就是为什么

My problem was creating a minimal-pain Wordpress theme framework with Webpack that automates the more tedious parts.我的问题是使用 Webpack 创建一个最小痛苦的 Wordpress 主题框架,它可以自动化更乏味的部分。 (I know it's a mouthful) (我知道这是一口)

I needed to inject an async script tag for browser-sync to connect with the page.我需要为浏览器同步注入一个异步脚本标签以与页面连接。 But(like you) I couldn't find a way to universally attach a script to the page without a bit of boilerplate.但是(像您一样)我找不到一种方法可以在没有一点样板的情况下将脚本普遍附加到页面上。

So I made a plugin that put the string I needed into each file that contained the string </body> , because that would mean it was a full-page template and I wanted each full page template to automatically refresh when I updated the source file.所以我制作了一个插件,将我需要的字符串放入包含字符串</body>每个文件中,因为这意味着它是一个整页模板,我希望每个整页模板在我更新源文件时自动刷新.

It works!有用!

The only issue I've found is having to escape an already escaped backslash, because the output is run through a compiler before actually being html in the browser.我发现的唯一问题是必须转义已经转义的反斜杠,因为输出在浏览器中实际成为 html 之前通过编译器运行。

So just be warned you might have to fudge it a bit, and there are no doubt more problems like that someone will run into.所以请注意,您可能需要稍微捏造一下,毫无疑问,有人会遇到更多类似的问题。

But I'll go out on a limb and say this looks like the solution to what you were originally asking.但是我会冒昧地说这看起来像是您最初要求的解决方案。

Again, the plugin:再次,插件:

https://github.com/smackjax/html-webpack-inject-string-plugin https://github.com/smackjax/html-webpack-inject-string-plugin

If it's not what you're looking for or you have problems, let me know!如果这不是您要查找的内容或遇到问题,请告诉我!

Maybe you can use html-webpack-plugin/template-option and raw-loader .也许你可以使用html-webpack-plugin/template-optionraw-loader

BTW, you need to use default property, if you get [object Module] result.顺便说一句,如果你得到[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>

For me the easiest way is to do this:对我来说,最简单的方法是这样做:

// webpüack.config.js
new HtmlWebpackPlugin({
    template: 'index.html',
    templateParameters: {
        foo: process.env.BAR,
    },
}),
<!-- index.html -->
<% if (foo) { %>
    <script src="bar.min.js"></script>
<% } %>

Works like a charm奇迹般有效

use this settings.使用此设置。

template: root to your html file模板:根到您的 html 文件

new HtmlWebpackPlugin({
    title: "chucknorris-app",
    template: "./src/template.html",
}),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 DOMParser 附加<script> tags to <head>/<body> but not executing - DOMParser appending <script> tags to <head>/<body> but not executing 是<script> tags outside <head> and <body> permitted in HTML? - Are <script> tags outside <head> and <body> permitted in HTML? 如何使用jsdom序列化没有head和body标签的HTML - How to serialize HTML without head and body tags using jsdom 如何修复脚本标记中使用的注释语法? - How do I fix the comment syntax used inside script tags? 我们如何向其中包含的所有<a>标签</a>添加下载属性 <body></body> 标签(使用JavaScript)? - How can we add a download attribute to all the <a> tags present inside <body></body> tag (using JavaScript)? 如何使用JavaScript将脚本,链接和元标记附加到头部? - How to append script, link, and meta tags onto head using JavaScript? 如何选择某些其他标签内的标签 - how to select tags that are inside certain other tags 脚本标签在HTML文档中的位置- <head> 和 <body> 有不同的行为 - Position Of Script Tags In HTML Document - <head> & <body> Has Different Behaviour Javascript在内部不起作用 <head> 要么 <body> 标签 - Javascript doesn't work inside <head> or <body> tags 如何使用jquery和/或javascript在textarea内查找链接标记并将其转换为@import标记? - how do i find and convert link tags to @import tags inside a textarea using jquery and/or javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM