4

I am building a Angular2 library that defines some Components. I am trying to publish this library as an npm module and then npm install and use it in my other Angular2 projects.

I followed tutorials like [1] and [2]. This got me to a point where I can successfully import Services and Components that define their template inline (like template: '<p>hello world</p>') from my library.

However, when I import Components that define their template in a separate file using templateUrl: 'app/hello-world.component.html', my app that is importing this component tries to load the template file relative in my project directory rather than in the node_modules/ directory of the installed library. Obviously this results in an error:

404 Not Found - http://localhost:3000/app/hello-world.component.html

Is there a way to publish an Angular2 library that uses templateUrls in Components? Or is there a workaround, like a tool that can automatically inline any templateUrl references when transpiling my TypeScript Components to JavaScript?

In case this is relevant: I am currently using SystemJS.

1 Answer 1

3

Inlining templates is important for performance reasons also, so it does make sense to get them inlined before publishing a package. Only for quick development it is a hurdle.

My solution is to use the gulp extension gulp-inline-ng2-template to create an inlined version of my code and reference the library in the dist rather than the app folder from my other projects.

gulpfile.js:

var gulp = require('gulp'),
    inlineNg2Template = require('gulp-inline-ng2-template');

gulp.task('inline-templates', function () {
    return gulp.src('app/**/*.ts')
        .pipe(inlineNg2Template({useRelativePaths: true, indent: 0, removeLineBreaks: true}))
        .pipe(gulp.dest('dist'));
});
Sign up to request clarification or add additional context in comments.

1 Comment

This one actually works, but i lost more than half hour for using realtive paths for templates, and finally found problem that UseRelativePaths should be camelCase instead of PascalCase.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.