javascript - 使用 Html Webpack 插件时如何在 <head> 和 <body> 标签内添加某些脚本标签

标签 javascript webpack html-webpack-plugin

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

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

例子:

我该怎么办,

  1. 添加<script> alert('in head tag') </script>里面 <head>标记为第一个 child
  2. 添加<script> alert('in body tag') </script>里面 <body>标记为第一个 child

这是我的 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 文件并在 headbody< 中添加这两个脚本标签.

我猜您要问的是“如何将生成的包插入模板的两个不同区域?”。如果是这样的话,就会有一个 section在提到传递给模板文件的数据的文档中:

"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: {
  head: './src/file1.js',
  body: './src/file2.js',
}

你的插件设置为

new HtmlWebpackPlugin({
  template: './src/pages/app.page.ejs' // note the .ejs extension
})

然后 app.page.ejs 应该能够从插件访问数据,您可以将这些条目放在任何您想要的地方。有一个很大的 ejs example file在他们的 repo 协议(protocol)中。一个更简单的示例,一个更具体到您的用例的示例是:

<!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>

关于javascript - 使用 Html Webpack 插件时如何在 <head> 和 <body> 标签内添加某些脚本标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51285711/

相关文章:

javascript - React Native AsyncStorage getItem 返回 promise 而不是值(value)

php - 获取多维数组

javascript - ag-grid 列文本 chop 问题

reactjs - css-loader 不导入 .css 文件返回空对象

javascript - Webpack 不会在不重新启动服务器的情况下捆绑对某些文件的更改

javascript - 使用 Apps 脚本抓取 javascript 渲染的网页

webpack - Vue.js - 将 CSS (SCSS) 从单个 *.vue 文件中分离出来

webpack - HtmlWebpackPlugin 不输出任何内容

javascript - 错误 : Cannot find module 'html-webpack-plugin' - Webpack (React)

javascript - Webpack,html-webpack-plugin,错误: Child compilation failed