Webpack 没有在我的 JS 文件中捆绑所有函数

Webpack doesn't bundle all functions in my JS file

我最近将 Webpack 集成到我的项目中,以便为我网站上的 JS 文件构建捆绑包。解决了一些小问题后,我就可以构建捆绑包了。在浏览器中检查后,Javascript 代码之一引发了以下错误。

检查后,我意识到 addComment.moveform 导致了问题。

因此,我检查了生成的包,发现变量 addComment 的定义还没有被推送到包中。 Javascript 写成下面的有没有不被捆绑的原因?没有 Webpack 抛出错误?

 /**
 * 'Comment Reply' to each comment.
 * This script moves the Add Comment section to the position below the appropriate comment.
 * Modified from Wordpress https://core.svn.wordpress.org/trunk/wp-includes/js/comment-reply.js
 * Released under the GNU General Public License - https://wordpress.org/about/gpl/
 */
var addComment = {
  moveForm: function(commId, parentId, respondId, postId) {
    var div,
      element,
      style,
      cssHidden,
      t = this,
      comm = t.I(commId),
      respond = t.I(respondId),
      cancel = t.I("cancel-comment-reply-link"),
      parent = t.I("comment-replying-to"),
      post = t.I("comment-post-slug"),
      commentForm = respond.getElementsByTagName("form")[0];

    if (!comm || !respond || !cancel || !parent || !commentForm) {
      return;
    }

    t.respondId = respondId;
    postId = postId || false;

    if (!t.I("sm-temp-form-div")) {
      div = document.createElement("div");
      div.id = "sm-temp-form-div";
      div.style.display = "none";
      respond.parentNode.insertBefore(div, respond);
    }

    comm.parentNode.insertBefore(respond, comm.nextSibling);
    if (post && postId) {
      post.value = postId;
    }
    parent.value = parentId;
    cancel.style.display = "";

    cancel.onclick = function() {
      var t = addComment,
        temp = t.I("sm-temp-form-div"),
        respond = t.I(t.respondId);

      if (!temp || !respond) {
        return;
      }

      t.I("comment-replying-to").value = "0";
      temp.parentNode.insertBefore(respond, temp);
      temp.parentNode.removeChild(temp);
      this.style.display = "none";
      this.onclick = null;
      return false;
    };

    /*
     * Set initial focus to the first form focusable element.
     */
    document.getElementById("comment-form-message").focus();

    /*
     * Return false so that the page is not redirected to HREF.
     */
    return false;
  },

  I: function(id) {
    return document.getElementById(id);
  }
};

这可能是因为死代码消除a.k.a。 tree shaking:如果 Webpack 注意到一个特定的函数没有被使用,它就会把它留下来生成一个更小的包。但是 Webpack 只知道 从 JavaScript 调用的函数,不知道从 HTML.

中硬编码的事件处理程序调用的函数

解决此问题的最简单方法是遵守 Webpack 的规则,并通过 JavaScript 附加您的事件处理程序。无论如何,这是更好的做法,因为 various reasons.

如果您需要将数据传递给事件处理程序(就像您在此处所做的那样),您可以在元素上使用 data attributes 并在事件处理程序函数中读出数据。