Webpack --watch入口main.ts执行完成后能否执行extend.ts代码?
webpack --watch with main.ts as entry? Great question! Let's break this down based on how Webpack works—keep in mind webpack --watch only handles automatic re-packaging when files change; it doesn't alter the core execution logic of your bundled code.
The short answer:
Only if you explicitly connect extend.ts to your main entry's dependency graph. Webpack only bundles (and thus runs) code that's reachable from your entry file.
Here's the detailed breakdown:
If you don't reference
extend.tsinmain.ts(or any module thatmain.tsimports):
Webpack will completely ignoreextend.ts—it won't be included in the bundled output at all. So it will never run, even withwebpack --watchenabled. Webpack builds bundles based on a dependency tree starting from your entry point; if a file isn't part of that tree, it gets left out.If you want
extend.tsto run aftermain.ts:
You need to importextend.tsinmain.ts, preferably at the end of your main code to ensure it runs after main's logic completes. For example:// main.ts // Your existing main code here console.log('Main.ts execution complete'); // Import extend.ts to trigger its execution after main import './extend.ts';// extend.ts console.log('Extend.ts running after main.ts!');When you run
webpack --watch, Webpack will bundle both files together. Since the import is synchronous,extend.ts's code will execute right after the lines above it inmain.ts.
Alternative: Multiple entries (if you need separate bundles)
If you don't want to import extend.ts directly in main.ts, you can configure Webpack with multiple entries in your webpack.config.js:
module.exports = { entry: { main: './src/main.ts', extend: './src/extend.ts' }, // ... other config };
But this will generate two separate bundle files. To get extend.ts to run after main.ts, you'd need to load both bundles in your HTML (load main.js first, then extend.js).
Remember, webpack --watch just rebuilds your bundle whenever you save changes to your files—it doesn't alter the order or execution of your code. The key is making sure extend.ts is part of the bundled output one way or another.
内容的提问来源于stack exchange,提问作者Shri

