【问题标题】:how to use angular 8 with webpack in rails 6 app?如何在 Rails 6 应用程序中使用 Angular 8 和 webpack?
【发布时间】:2019-09-24 03:50:35
【问题描述】:

我正在阅读电子书Rails、Angular、Postgres 和 Bootstrap,第二版。我真的学到了很多东西。这些书来自 2017 年,但我正在尝试创建更新所有框架的项目。我想要艰难的道路。呵呵

所以我使用的是 Rails 6 和 Angular 8。当我试图在 webpack 中为 Angular 创建一个组件时,我被卡住了。怎么样?

我只会描述我认为必要的步骤,所以这就是我所做的:

我创建了 rails 项目:

rails new angular-on-rails

然后我用 webpacker 添加了 angular:

rails webpacker:install:angular

之后我创建了一个简单的视图:

rails g controller dashboard index

然后,在这个视图中,我添加了这段代码:

<hello-angular></hello-angular>
<%= javascript_pack_tag "hello_angular" %>

有效!我可以在浏览器中看到 Hello Angular。

之后我尝试创建一个名为 hello-component 的组件:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'hello-component',
  template: `<h1>Hello component</h1>`
})
export class HelloComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

console.log("Hello Component")

不要忘记更新 app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello-component/hello-component.component'

@NgModule({
  declarations: [
    AppComponent,
    HelloComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

还有 index.html.erb:

<hello-angular></hello-angular>
<hello-component></hello-component>
<%= javascript_pack_tag "hello_angular" %>

我在浏览器中看不到 Hello 组件,浏览器控制台上也没有错误,它仅显示 hello-component ts 文件中的 console.log。所以文件正在加载,但没有渲染......我错过了什么?

如果你想看看,我把这个简单的项目放在repository 中。

感谢您的宝贵时间!

【问题讨论】:

    标签: ruby-on-rails angular webpack


    【解决方案1】:

    从 angular 和 rails 开始,最简单的方法是从头开始创建一个项目: 我个人将 rvm 用于 ruby​​ gem 集和版本管理、nvm(节点版本管理器)、yarn 和 npm(javascript 包管理器)

    目前,我认为 react 比 angular 更容易集成,因为 angular 是一个完整的框架,不像 React 那样只是一个前端库,所以 react 混合得更好,真的与 Angular 有两个应用程序。

    rails new testing_angular -B --webpackt=angular
    

    之后,进入项目内部

     cd testing_angular
     bundle install
     rails webpacker:install
     rails webpacker:install:angular
    

    终于我们有了所有的开始,去使用你最喜欢的文本编辑器吧 在这一点上,我认为反应的性质与轨道比角度更好, 但这只是我的意见。

    这里有基本的 Rails 应用程序,可以轻松运行

    RAILS_ENV=development bundle exec rails server -b 0.0.0.0
    

    还有一个完整的 Angular 应用在​​ app/javascript/hello_angular。

    我们需要用一个新的控制器来调用这个应用程序

    rails g controller hello_angular index
    

    并在 /config/routes.rb 中添加必要的路由

    cat config/routes.rb
    Rails.application.routes.draw do
    
      root 'hello_angular#index'
      get 'hello_angular/index'
    
    end
    

    改变视图以像这样呈现角度:

    ➜ cat app/views/hello_angular/index.html.erb
    <div>
      <hello_angular></hello_angular>
    </div>
    <%= javascript_pack_tag 'hello_angular' %>
    

    这样它应该可以工作,但我们需要先解决一些问题:

    第一:

    按顺序将文件 custom.js 添加到 config/webpack

    cat > config/webpack/custom.js
    const webpack = require('webpack')
    const path = require('path')
    module.exports = {
      plugins: [
          new webpack.ContextReplacementPlugin(
            /angular(\\|\/)core/,
            root('../../app/javascript/hello_angular'), // location of your src
            { }
          )
      ]
    }
    function root(__path) {
      return path.join(__dirname, __path);
    }
    

    二次编辑 development.js

    ➜ cat config/webpack/development.js
    process.env.NODE_ENV = process.env.NODE_ENV || 'development'
    
    const environment = require('./environment')
    const {merge} = require('webpack-merge') // update from previous
    
    const customConfig = require('./custom')
    
    module.exports = merge(environment.toWebpackConfig(), customConfig)
    

    那么我们需要添加一些依赖:

    yarn add webpack-merge
    

    我认为这是我们需要修复的两个错误。

    1) yarn add core-js@^2.5.0
    if the project cannot load corejs/es7reflect
    
    1. ERROR 错误:“选择器“hello-angular”与任何元素都不匹配”

    你需要修改这个:

     cat app/javascript/hello_angular/app/app.component.ts
    import { Component } from '@angular/core';
    
    @Component({
      selector: 'hello_angular', <= fix this selector
      template: `<h1>Hello {{name}}</h1>`
    })
    export class AppComponent {
      name = 'Angular!';
    } 
    

    终于可以加载项目了:

    RAILS_ENV=开发包 exec rails server -b 0.0.0.0

    Started GET "/" for 127.0.0.1 at 2019-10-18 23:00:58 +0200
       (0.5ms)  SELECT sqlite_version(*)
    Processing by HelloAngularController#index as HTML
      Rendering hello_angular/index.html.erb within layouts/application
    [Webpacker] Compiling…
    [Webpacker] Compiled all packs in /Users/toni/learn/ruby/ruby-way/angular-way/testing_angular/public/packs
      Rendered hello_angular/index.html.erb within layouts/application (Duration: 9940.3ms | Allocations: 4452)
    Completed 200 OK in 12213ms (Views: 12208.3ms | ActiveRecord: 0.0ms | Allocations: 2022052)
    

    然后它真的像一个 pi 一样工作,让我们预先准备这个端点,在路由中添加一个路由,并向 hello_angular 控制器添加一个方法

    http://localhost:3000/hello_angular/world?name=Calimero
    
    {
    
        "name": "Calimero"
    
    }
    

    并将方法添加到之前创建的控制器中:

    class HelloAngularController < ApplicationController
      def index
      end
    
      
      def world
        name = params[:name] || 'world'
        render json: { name: name }
      end
    end
    

    然后以角度呈现它:

    testing_angular on  master [?] is ? v0.1.0 via ⬢ v12.4.0 via ? ruby-2.6.3@way took 39m 30s
    ➜ cat app/javascript/hello_angular/app/app.component.ts
    import { Component } from '@angular/core';
    import {HttpClient} from '@angular/common/http';
    
    @Component({
      selector: 'hello_angular',
      template: `<h1>Hello {{name}}</h1>
                 <button (click)="changeName()">Change Name!</button>`
    })
    export class AppComponent {
        name = 'Angular!';
    
      constructor(private http: HttpClient){}
    
      changeName() {
        this.http.get('/hello_angular/world').subscribe(data => {
          this.name = data['name'];
        });
      }
    }
    
    testing_angular on  master [?] is ? v0.1.0 via ⬢ v12.4.0 via ? ruby-2.6.3@way
    ➜ cat app/javascript/hello_angular/app/app.module.ts
    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import {HttpClientModule} from '@angular/common/http';
    
    import { AppComponent } from './app.component';
    
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
          BrowserModule,
          HttpClientModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    

    终于可以运行 Angular 应用了,请在此处查看 ifnal 参考以及完整的源代码:

    https://github.com/anquegi/testing-angular

    请检查以下参考资料:

    1. https://github.com/amitai10/rails-angular-webpacker
    2. https://medium.com/swlh/getting-started-with-rails-6-and-react-afac8255aecd[4]
    3. https://www.pluralsight.com/guides/react-vs-angular-2-integration-with-rails

    【讨论】:

    • 非常感谢您的回答。感谢您的时间!并感谢您的所有参考!
    • 我尝试了这种方法,一切正常,直到我添加了“templateUrl”。你知道如何解决这个问题吗?
    【解决方案2】:

    我认为您还需要将 HelloComponent 添加到 bootstrap 数组中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-13
      • 2022-08-12
      • 2017-08-11
      • 2020-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多