使用HtmlWebackPlugin时如何在<head>和<body>标记内添加某些脚本标记

Gre*_*ple 6 javascript webpack html-webpack-plugin

我正在使用HtmlWebpackPlugin用javascript生成HTML文件。

现在,我想在<head><body>标签的不同部分添加自定义脚本

例:

我如何,

  1. <script> alert('in head tag') </script><head>标签内添加第一个孩子
  2. <script> alert('in body tag') </script><body>标签内添加第一个孩子

这是我的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
        }
    })
Run Code Online (Sandbox Code Playgroud)

M T*_*eer 12

我知道我迟到了,但这就是我解决问题的方法。我可能会帮助别人。

  1. 我禁用了资产的自动注入inject:false
new HtmlWebpackPlugin({
  hash: true, // hash for cache bursting
  template: "index.html", // source template
  minify: true, // should html file be minified?
  inject: false,
}) 
Run Code Online (Sandbox Code Playgroud)
  1. 模板文件中手动渲染的资源。

css 在头部

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

js在体内

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

您实际上可以在这里进行任何类型的过滤/排序。

您可以在此处查看可用选项以及如何使用它们。

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


the*_*cks 11

您的问题有点令人困惑。这意味着您要向模板添加静态脚本标签。如果这是你只需要进入你的情况src/pages/app.page.html文件,并在添加这两个脚本标记headbody

我想您要问的是“如何在模板的两个不同区域中插入生成的包?” 。如果是这种情况,则文档中会有一个部分提到将什么数据传递到模板文件:

"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": []
      },
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

所以如果你entry看起来像

entry: {
  head: './src/file1.js',
  body: './src/file2.js',
}
Run Code Online (Sandbox Code Playgroud)

并且您的插件设置为

new HtmlWebpackPlugin({
  template: './src/pages/app.page.ejs' // note the .ejs extension
})
Run Code Online (Sandbox Code Playgroud)

然后app.page.ejs应该能够从插件访问数据,并且可以将这些条目放置在所需的位置。他们的仓库中有一个很大的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>
Run Code Online (Sandbox Code Playgroud)

请注意,我没有使用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;
Run Code Online (Sandbox Code Playgroud)

模板看起来像

<!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>
Run Code Online (Sandbox Code Playgroud)


IVO*_*LOV 3

您可以使用官方示例中所示的模板参数

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'
    })
  ]
};
Run Code Online (Sandbox Code Playgroud)