首页 文章

如何npm发布一个带有单独的templateUrl html文件的Angular2组件?

提问于
浏览
3

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

我按照[1][2]这样的教程 . 这让我能够成功导入从我的库中定义其内联模板(如 template: '<p>hello world</p>' )的服务和组件 .

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

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?

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

1 回答

  • 3

    内联模板对于性能原因也很重要,因此在发布包之前让它们内联是有意义的 . 只有快速发展才是障碍 .

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

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

相关问题