Search code examples
typescriptrequirejs

Typescript RequireJS import files


I have a basic question about RequireJS.

Currently i generate my Typescript files into a single outfile JS file. If i were to start using RequireJS, does this mean this single JS file would be eliminated?

My understanding is that RequireJS loads the JS file references at run-time. Is this correct?


Solution

  • If i were to start using RequireJS, does this mean this single JS file would be eliminated?

    Not at all. You could still output everything to a single file. If you tell TypeScript to produce AMD modules and let it produce multiple files, you end up with a one-to-one relation between files and AMD modules: each file contains exactly one AMD module, and each AMD module is contained by exactly one file. If you tell TypeScript to produce a single file, you end up with a bundle of AMD modules: a single file contains multiple modules.

    In all projects where I used AMD, I had TypeScript produce individual files and then processed the results with r.js (RequireJS' own optimizer) or Webpack. I suppose though there may be projects where letting TypeScript itself produce the bundle is a viable option. It really depends on the project.

    My understanding is that RequireJS loads the JS file references at run-time. Is this correct?

    This is true but it does not determine how you should organize your project at run time. Typically, a project will have a set of modules that won't run at all unless they are all loaded together, and these modules should be made into a bundle so as to load them in a single request instead of having to make a dozen requests to the server. Ultimately, you need to bundle modules in a way that makes sense for your project.