10

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?

    1 Answer 1

    10

    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(); } } 
    2
    • 2
      pin "@noty", to: "lib/noty.js", preload: true does not work for me. The browser keeps telling Relative references must start with either "/", "./", or "../"..CommentedJan 3, 2023 at 8:17
    • 2
      @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
      CommentedMar 16, 2023 at 21:56

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.