【问题标题】:Webpacker in Rails Project using angular cannot import .html.erb and .css from external templateRails 项目中使用 Angular 的 Webpacker 无法从外部模板导入 .html.erb 和 .css
【发布时间】:2017-07-10 01:40:22
【问题描述】:

我在我的项目中使用 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']

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

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

【问题讨论】:

  • 您好,您找到解决方案了吗?我已经得到了 Manish Kongari 的解决方案,但它只允许我加载 .html 文件,而不是 .html.erb 我尝试了 rails-erb-loader ...但它似乎期望 .js.erb 的 js 内容,所以当它加载我的 .html.erb ... 语法错误时:D 你有没有找到其他的尝试?

标签: angular webpack ruby-on-rails-5 webpacker


【解决方案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!'
}

【讨论】:

  • 此解决方案允许加载 .html 模板,但不加载 .html.erb 是吗?
【解决方案2】:

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

声明一个模块

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

在 webpacker 中更新 style 加载器

config/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!';
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-17
  • 1970-01-01
  • 2019-07-19
  • 2020-03-02
  • 2021-03-10
  • 2017-05-11
  • 2018-06-14
相关资源
最近更新 更多