Webpack仅编译自执行代码,不编译自定义函数的问题求助
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

