How can I concat TypeScript files with Angular2 li

2019-05-07 18:37发布

问题:

How can I concat multiple TypeScript with Angular2 files into single JS file like Rails assets:precompile?

For example, in a tutorial of angular2 official page, you see four .ts files:

  • app.component.ts
  • boot.ts
  • hero.ts
  • hero-detail.component.ts

and when you look at app.component.ts file, you see the following part:

import {Hero} from './hero';
import {HeroDetailComponent} from './hero-detail.component';

It works perfectly when you compile all .ts files separately, but I'd like to concat() them into one single .js file so that there would be less http requests. I'm using gulp, and tried gulp-concat, which didn't work. browserify neither.

Would anyone help? Thanks in advance.

回答1:

It sounds like you're looking for something like Webpack. Webpack will transpile your ts files to js and then create a single module bundle that you can include with a <script> tag. Not only will it transpile your code but it will also build in its dependencies including Angular 2 itself (and its dependencies).

Here's a simple starter project for Angular 2 and Webpack written by one of the Angular 2 developers: https://github.com/pkozlowski-opensource/ng2-webpack-play



回答2:

It looks like typescript will support concatenating multiple files(with modules) from version 1.8 onwards(1.7.5 is current). There is also another way using webpack, but I don't know how it is done exactly.



回答3:

I use JSPM to make my angular2 projects production ready. Other popular tools like JSPM include webpack, and browserfy. One of the important tasks that JSPM will accomplish is to bundle the various modules that make up your angular2 project. I also set the "selfExecutingBundle" flag to true and have JSPM make one bundled js file (e.g. myApp.bundled.js) and from there I minify it (myApp.bundled.min.js) and this one script reference is used in the index.html file.

<html>

<head>
    <title>Hello Angular World</title>
</head>
<body>
<div>
    <my-app>Loading...</my-app>
</div>
    <script src="/js/myApp.bundle.min.js"></script>
</body>

</html>

And that is all you need!

In the future when the HTTP/2 spec is more common, there may be less of a need to bundle your module-based projects, but for now I think bundling is needed.