简体   繁体   English

如何使用单独的templateUrl html文件npm发布Angular2组件?

[英]How to npm publish an Angular2 Component with separate templateUrl html file?

I am building a Angular2 library that defines some Components. 我正在建立一个定义一些组件的Angular2库。 I am trying to publish this library as an npm module and then npm install and use it in my other Angular2 projects. 我试图将此库发布为npm模块,然后npm install并在我的其他Angular2项目中使用它。

I followed tutorials like [1] and [2] . 我遵循了[1][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. 这使我可以成功地从我的库中导入定义其内联模板的服务和组件(例如template: '<p>hello world</p>' )。

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. 但是,当我导入使用templateUrl在单独文件中定义其模板的组件时templateUrl: 'app/hello-world.component.html' ,导入此组件的应用程序尝试将模板文件相对于我的项目目录而不是项目已安装库的node_modules/目录。 Obviously this results in an error: 显然,这会导致错误:

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

Is there a way to publish an Angular2 library that uses templateUrl s in Components? 有没有办法发布在Components中使用templateUrl的Angular2库? Or is there a workaround, like a tool that can automatically inline any templateUrl references when transpiling my TypeScript Components to JavaScript? 还是有一种解决方法,例如一种在将TypeScript组件转换为JavaScript时可以自动内联任何templateUrl引用的工具?

In case this is relevant: I am currently using SystemJS. 如果这是相关的:我当前正在使用SystemJS。

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. 我的解决方案是使用gulp-inline-ng2-template扩展名gulp-inline-ng2-template创建代码的内联版本,并引用dist的库而不是其他项目中的app文件夹。

gulpfile.js: 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'));
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM