【问题标题】:Webpack compiles self invoke functions only, not the any other functionWebpack 只编译自调用函数,不编译任何其他函数
【发布时间】:2021-03-09 14:21:44
【问题描述】:

我正在使用 Webpack 将我所有的 .js 文件编译并打包为一个。它编译导入的 jquery 和 bootstrap 文件,但是当涉及到我自己在 main.js 中的代码时,如下所示,它只编译 console.log('Hello World'); 而不是 searchTable 或任何其他函数。

import jQuery from 'jquery';
import bootstrap from '../../../node_modules/bootstrap/dist/js/bootstrap.bundle';

console.log('Hello World');

const searchTable = (tableId) => {
    const input = document.querySelector('#tableSearchInput');
    const filter = input.value.toUpperCase();
    const table = document.querySelector('#' + tableId);
    const tr = table.getElementsByTagName('tr');

    for (i = 0; i < tr.length; i++) {
        const td = tr[i].getElementsByTagName('td')[0];
        if (td) {
            const txtValue = td.textContent || td.innerText;
            if (txtValue.toUpperCase().indexOf(filter) > -1) {
                tr[i].style.display = "";
            } else {
                tr[i].style.display = "none";
            }
        }
    }
};

Webpack.config.js 文件

const path = require('path');

module.exports = {
    entry: './public/src/js/main.js',
    output: {
        path: path.resolve(__dirname, './public/dist/js'),
        publicPath: '',
        filename: 'app.js'
    },
    mode: 'production'
};

我搜索了很多,但找不到答案。
您的帮助可能会拯救我,我将不胜感激!

【问题讨论】:

  • 您没有使用searchTable,也没有导出它。 Webpack 有一个 tree-shaking 过程,可以删除未使用的代码
  • @GuerricP 非常感谢,您的评论对我有帮助,是的,确实如此。现在在脚本中调用函数后它确实可以工作了。

标签: javascript node.js webpack webpack-5


【解决方案1】:

Webpack 有一个称为 Tree Shaking 的过程。 Tree Shaking 或死代码消除意味着在构建过程中未使用的模块不会包含在包中。
webpack 等工具会检测死代码并将其标记为“未使用模块”,但不会删除代码。

要了解更多信息,您可以查看此链接:https://webpack.js.org/guides/tree-shaking/

【讨论】:

    猜你喜欢
    • 2019-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多