1

我在我的项目中使用 angular 4。我想将我的html.erb.css文件与 js 文件分开。我在我的component.ts文件中尝试了以下内容。我做了一些配置来使用 webpacker 文档加载外部 html。但它不允许我导入.html.erb文件。以及无法加载css文件。我也尝试加载 sass 文件但不工作。

import templateString from './templatestring.html.erb';
import styles from './styles.css';

在我的组件类中:

templateUrl: templateString,
styleUrls: ['./style.css']

这是给出错误并且不起作用。

请告诉我如何解决这个问题,我不想使用内联模板和样式表。

4

2 回答 2

1

在 css 方面,您在 webpakcer rpeo 中评论了相同的问题。https://github.com/rails/webpacker/issues/963

声明一个模块

declare module "*.css" {
  const content: string
  export default content
}

style在 webpacker 中更新加载器

配置/webpack/environment.js

const { environment } = require('@rails/webpacker')

environment.loaders.set('style', {
    test: /\.(scss|sass|css)$/,
    use: [{
        loader: "to-string-loader"
    }, {
        loader: "css-loader"
    }, {
        loader: "postcss-loader"
    }, {
        loader: "resolve-url-loader"
    }, {
        loader: "sass-loader"
    }]
})

module.exports = environment

导入 CSS

app/javascript/hello_angular/app/app.component.ts

import { Component } from '@angular/core';
import styleString from './app.component.css';

@Component({
  selector: 'hello-angular',
  template: `<h1>Hello {{name}}</h1>`,
  styles:[styleString]
})
export class AppComponent {
  name = 'Angular!';
}
于 2017-11-02T11:17:03.220 回答
1

请检查此https://github.com/rails/webpacker/blob/master/docs/typescript.md#html-templates-with-typescript-and-angular

yarn add html-loader

将 html-loader 添加到 config/webpack/environment.js

environment.loaders.set('html', {
  test: /\.html$/,
  use: [{
    loader: 'html-loader',
    options: {
      minimize: true,
      removeAttributeQuotes: false,
      caseSensitive: true,
      customAttrSurround: [ [/#/, /(?:)/], [/\*/, /(?:)/], [/\[?\(?/, /(?:)/] ],
      customAttrAssign: [ /\)?\]?=/ ]
    }
  }]
})

将 .html 添加到 config/webpacker.yml

  extensions:
    - .elm
    - .coffee
    - .html

设置自定义 d.ts 定义 // app/javascript/hello_angular/html.d.ts

declare module "*.html" {
  const content: string
  export default content
}

添加相对于 app.component.ts 的 template.html 文件

<h1>Hello {{name}}</h1>
Import template into app.component.ts
import { Component } from '@angular/core'
import templateString from './template.html'

@Component({
  selector: 'hello-angular',
  template: templateString
})

export class AppComponent {
  name = 'Angular!'
}
于 2017-10-09T05:18:51.347 回答