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

Webpack --watch入口main.ts执行完成后能否执行extend.ts代码?

Can extend.ts run after main.ts when using 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.ts in main.ts (or any module that main.ts imports):
    Webpack will completely ignore extend.ts—it won't be included in the bundled output at all. So it will never run, even with webpack --watch enabled. 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.ts to run after main.ts:
    You need to import extend.ts in main.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 in main.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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:25:02