本文介绍了如何npm发布带有单独的templateUrl html文件的Angular2组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个定义某些组件的Angular2库.我试图将此库发布为npm模块,然后发布npm install并在其他Angular2项目中使用它.

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.

我遵循了 [1] [2] .这样一来,我就可以成功地从库中导入定义内联模板(如template: '<p>hello world</p>')的服务和组件.

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.

但是,当我使用templateUrl: 'app/hello-world.component.html'导入在单独文件中定义其模板的组件时,正在导入该组件的应用尝试将相对的模板文件加载到我的项目目录中,而不是在node_modules/目录中已安装的库.显然,这会导致错误:

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:

是否可以发布在组件中使用templateUrl的Angular2库?还是有一种解决方法,例如一种在将TypeScript组件转换为JavaScript时可以自动内联任何templateUrl引用的工具?

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?

如果这是相关的:我当前正在使用SystemJS.

In case this is relevant: I am currently using 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.

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

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:

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'));
});

这篇关于如何npm发布带有单独的templateUrl html文件的Angular2组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 22:13