0

我正在尝试加载我的自定义 js。但出现错误。

错误如下。

无法注册控制器:通知(控制器/通知控制器)错误:无法解析从 http://localhost:3000/assets/controllers/notification_contr 导入的说明符“@noty”...

│   ├── javascript
│   │   ├── application.js
│   │   ├── controllers
│   │   │   ├── application.js
│   │   │   ├── index.js
│   │   │   ├── notification_controller.js
│   │   └── lib
│   │       └── noty.js

通知控制器.js

import { Controller } from "@hotwired/stimulus"
import Noty from "@noty"

export default class extends Controller {
  static targets = [ 'type', 'message' ]

  ....// some codes.

}

配置/importmap.rb

# Pin npm packages by running ./bin/importmap

pin "application", preload: true
pin "@hotwired/turbo-rails", to: "turbo.min.js", preload: true
pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true
pin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true
pin_all_from "app/javascript/controllers", under: "controllers"

## lib
pin "@noty", to: "app/javascript/lib/noty.js", preload: true

我做错了什么?我还有一些其他问题是,“stimulus.min.js”和“turbo.min.js”文件存在哪里?

4

1 回答 1

0

您的错误是因为您需要修复路径

pin "@noty", to: "app/javascript/lib/noty.js", preload: true

pin "@noty", to: "lib/noty.js", preload: true

Noty但是,由于库导出模块的方式,您将遇到更多导​​入问题。添加库的最简单方法是通过资产管道。

去做这个

  1. 添加noty.jsapp/assets/config
  2. 添加noty.cssapp/assets/stylesheets
  3. 添加//= link noty.jsapp/assets/config/manifest.js
  4. 将此添加到app/views/layouts/application.html.erb
<%= stylesheet_link_tag "noty" %>
<%= javascript_include_tag "noty" %>

完成后,Noty应该可以在您的 js 控制器中使用。例如

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = [ 'type', 'message' ]

  test(){
    var noty = new Noty({text: 'Hi!'});
    noty.show();
  }
}
于 2022-03-01T16:58:56.727 回答