4

I would like to use the code splitting feature provided by webpack in order to create several bundles of my app, developed using typescript, and load them on demand. I have been searching for a solution on line for a while and the closest answer I have found is this one: https://github.com/TypeStrong/ts-loader/blob/master/test/execution-tests/babel-codeSplitting/require.d.ts

This example is directly taken form the official ts-loader documentation and it shows how to rely on require.ensure in order to create a split point.

The thing that bugs me is that there is no a straightforward way in typescript to do that. The require.ensure function must be directly invoked in typescript. The following declaration file needs to be provided to allow typescript to silently digest that call:

declare var require: {
    <T>(path: string): T;
    (paths: string[], callback: (...modules: any[]) => void): void;
    ensure: (paths: string[], callback: (require: <T>(path: string) =>   T) => void) => void;
};

Is there a more elegant way to achieve the same result?

Caleb
  • 2,197
  • 3
  • 19
  • 31

1 Answers1

0

Is there a more elegant way to achieve the same result

No. Various runtimes have different (inconsistent) APIs for loading modules on demand. So TypeScript choses to be agnostic here.

More

Some notes on lazy loading and how it works in terms of Type safety : https://basarat.gitbooks.io/typescript/content/docs/project/external-modules.html

basarat
  • 261,912
  • 58
  • 460
  • 511
  • Thanks for the reply @basarat! I thought there was another way... but this seems to be the better approach. Your book is a good resource, thanks for sharing! – Giovanni Di Santo Sep 13 '16 at 13:56