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

Ami*_*avi 1 javascript webpack webpack-4

我最近将 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);
  }
};
Run Code Online (Sandbox Code Playgroud)

Tho*_*mas 5

这可能是因为死代码消除(又称树摇动):如果 Webpack 注意到某个特定函数没有被使用,它只会将其留下以生成更小的包。但 Webpack 只知道从 JavaScript调用的函数,而不知道从 HTML 中硬编码的事件处理程序调用的函数。

解决此问题的最简单方法是遵循 Webpack 的规则,并通过 JavaScript 附加事件处理程序。出于各种原因,无论如何这是更好的做法。

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