9

I am trying to load my custom js. but getting errors.

Error is following.

Failed to register controller: notification (controllers/notification_controller) Error: Unable to resolve specifier '@noty' imported from http://localhost:3000/assets/controllers/notification_contr...

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

notification_controller.js

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

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

  ....// some codes.

}

config/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

What did I do wrong? also some other questions I have is, where "stimulus.min.js" and "turbo.min.js" file exist?

Jin Lim
  • 1,759
  • 20
  • 24

1 Answers1

8

Your error is because you need to fix the path

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

to

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

However, you are going to run into more problems importing Noty because of how the library exports modules. The easiest way to add the library is through the asset pipeline.

To do this

  1. Add noty.js to app/assets/config
  2. Add noty.css to app/assets/stylesheets
  3. Add //= link noty.js to app/assets/config/manifest.js
  4. Add this to app/views/layouts/application.html.erb
<%= stylesheet_link_tag "noty" %>
<%= javascript_include_tag "noty" %>

Once this is done, Noty should be available in your js controllers. e.g.

import { Controller } from "@hotwired/stimulus"

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

  test(){
    var noty = new Noty({text: 'Hi!'});
    noty.show();
  }
}
Cameron
  • 756
  • 6
  • 16
  • 1
    `pin "@noty", to: "lib/noty.js", preload: true` does not work for me. The browser keeps telling `Relative references must start with either "/", "./", or "../".`. – Robert Reiz Jan 03 '23 at 08:17
  • 1
    @RobertReiz that browser console error message is known to the rails dev group, expected and of no further consquence. bit of a red herring... – Jerome Mar 16 '23 at 21:56