【问题标题】:Component relative path not working. Angular 2组件相对路径不起作用。角 2
【发布时间】:2017-01-02 23:25:12
【问题描述】:

我的配置如下,我想为组件使用相对路径。但它给了我这个错误:

404 获取 /js/some.component.html

我正在使用 SystemJS。

some.component.ts

import { Component, OnInit } from '@angular/core';
@Component({
    moduleId: module.id,
    selector: 'relative-path',
    templateUrl: 'some.component.html',
    styleUrls: ['some.component.css'],

})

export class SomeRelativeComponent {
}

app.component.ts

import { Component } from '@angular/core';
import { SomeRelativeComponent } from './some.component';
@Component({
  selector: 'my-app',
  template: `<h1>My First Angular 2 App</h1>
  <relative-path></relative-path>
  `,
  directives: [SomeRelativeComponent]
})
export class AppComponent { }

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false,
    "outDir": "./js"
  }
}

文件夹结构:

/js 目录下显然没有 some.component.html。但是,当我在 /app 目录中添加我的组件时,如何将其保存在那里?

【问题讨论】:

    标签: angular typescript systemjs


    【解决方案1】:

    在 ts.config.json 中,指定输出 .js 的输出目录。

    您需要修改outdir,或者您也可以使用Gulp 之类的工具,它允许您将文件作为流进行操作。然后,您可以定义任务,允许您将 .css / .js 文件移动、合并、缩小等。

    package.json

    "devDependencies": {
        "typescript": "^1.8.10",
        "typings": "^1.0.4",
        "gulp": "^3.9.1",
        "path": "^0.12.7",
        "gulp-clean": "^0.3.2",
        "gulp-concat": "^2.6.0",
        "gulp-typescript": "^2.13.1",
        "gulp-tsc": "^1.1.5",
        "run-sequence": "^1.2.2"
    }
    

    您需要在 package.json 中添加 gulp 依赖项,并使用 npm 安装它:https://www.npmjs.com/package/gulp

    然后在您的项目解决方案中的单个 gulpfile.cs 中,您可以定义任务,甚至使用观察者进行预编译,我觉得这非常有用。

    例如,由于您使用 TypeScript,

    gulpfile.js

    var destPathComponents = './wwwroot/app/';
    
    var tsProject = ts.createProject('tsconfig.json');
    gulp.task('Components_JS', function () {
        var tsResult = tsProject.src() // instead of gulp.src(...)
            .pipe(ts(tsProject));
    
        return tsResult.js.pipe(gulp.dest(destPathComponents));
    });
    

    NB:我不太确定这一点,但我记得像这样使用带有 gulp 的 tsconfig.json 实际上使用 tsconfig.json 文件的 outDir 值而不是你在 gulpfile.js 中设置的路径

    我真的推荐使用 Gulp。

    这是另一个使用简单 CSS 的 gulp 示例:

    gulp.task('Components_HTML', function () {
        return gulp.src([
            '*.html'
        ], {
            cwd: "Sources/**"
        })
            .pipe(gulp.dest(destPathComponents));
    });
    

    基本上,这定义了一个名为“Components_HTML”的 gulp 任务,它将获取所有 HTML 文件并将它们复制到目标路径,在我的例子中是 './wwwroot/app/'。 希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-12
      • 1970-01-01
      • 2013-02-19
      • 2015-08-30
      • 2011-03-17
      • 2014-06-25
      • 2018-09-15
      相关资源
      最近更新 更多