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?
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'));
});
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With