Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add JS HTML files to a @Template in Angular 2 (Like $templateCache)?

Tags:

angular

This is probably poorly worded, but in my existing Angular 1 projects I use a bunch of HTML resources that are precompiled into a JS file using HTML2JS. This works great so now I am considering my approach for Angular 2. Since HTML2JS has not been updated, everything seems to revolve around 2 strategies.

First you add the HTML inline inside the @tempate atScript. This caches it so I am not going to the server all of the time, but it also makes it difficult to format in IDEs and reduces readability IMHO.

The second is to use an external file and use the url inside of @template. This seems to make things more readable but limits the amount of caching. This means that I need to make larger server calls which I would like to avoid.

Is there a way to have a file start out in HTML then be compiled into a .js file and included in an Angular2 component?

like image 562
Jackie Avatar asked Apr 05 '15 13:04

Jackie


2 Answers

If you are using gulp to compile, you can use the angular-embed-templates plugin. Here I am loading the templateUrl into the template, before compiling to javascript in the dist folder, with source maps:

var gulp           = require('gulp');
var ts             = require('gulp-typescript');
var sourcemaps     = require('gulp-sourcemaps');
var embedTemplates = require('gulp-angular-embed-templates');

gulp.task('ts:build', function () {
    gulp.src('app/**/*.ts')
        .pipe(embedTemplates())
        .pipe(sourcemaps.init())
        .pipe(ts({
            noImplicitAny: true,
            module: 'system',
            target: 'ES5',
            experimentalDecorators: true,
            moduleResolution: 'node',
            emitDecoratorMetadata: true
        }))
        .pipe(sourcemaps.write())
        .pipe(gulp.dest('./dist'));
});
like image 164
Amrit Kahlon Avatar answered Nov 19 '22 20:11

Amrit Kahlon


Since Webpack is the new Gulp (also Gulp needs some help), here is what I came up with (uses stylus and jade)...

Use Webpack loaders like this...

loaders: [
  {
    include: /\.pug/,
    loader: 'pug-html-loader'
  },
  {
    test: /\.styl$/,
    loader: 'style-loader!css-loader!stylus-loader'
  },
  {
    test: /\.ts$/,
    loader: 'ts'
  }
]

Then use requires in your components like this...

@Component({
    ...
    template: String(require('./navbar.component.pug')),
    styles: [String(require('./navbar.component.styl'))],
    ...
})

Make sure to use styles and template instead of templateUrl and styleUrls

like image 32
Jackie Avatar answered Nov 19 '22 21:11

Jackie