You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Webpack仅编译自执行代码,不编译自定义函数的问题求助

Why Your searchTable Function Isn't Being Bundled by Webpack

Hey there! Let's break down why only your console.log statement and imported libraries are making it into your bundled app.js—your searchTable function is getting removed by Webpack's Tree Shaking feature, which is enabled by default in production mode.

The Root Cause

Tree Shaking works by detecting and removing unused code from your bundle. Since you've defined searchTable but haven't done any of the following:

  • Called it anywhere in your code
  • Exported it for use in other modules
  • Made it accessible to the global scope (like for use in HTML event handlers)

Webpack sees it as "dead code" and strips it out during the production build.

Fixes to Try

1. Make the function globally accessible (for use in HTML)

If you plan to call searchTable from your HTML (e.g., via onclick="searchTable('myTable')"), attach it to the window object so it's available outside your module:

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

console.log('Hello World');

const searchTable = (tableId) => {
    // Your existing function code here
};

// Attach to window to expose it globally
window.searchTable = searchTable;

2. Export the function for use in other modules

If you need to use searchTable in another JavaScript file, export it from main.js:

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

console.log('Hello World');

export const searchTable = (tableId) => {
    // Your existing function code here
};

Then import it wherever you need it:

import { searchTable } from './path/to/main.js';

// Call the function when needed
searchTable('myTable');

3. Temporarily disable Tree Shaking (not recommended)

If you just want to test without Tree Shaking (this will bloat your bundle, so avoid it for production), add this to your 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',
    optimization: {
        usedExports: false // Disables Tree Shaking
    }
};

After making one of these changes, re-run your Webpack build and check the app.js bundle—your searchTable function should now be included!

内容的提问来源于stack exchange,提问作者Masood

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 10:19:10