Skip to content

Instantly share code, notes, and snippets.

@Lumbe
Last active October 16, 2023 02:05
Show Gist options
  • Save Lumbe/131ce913ebd97b5c705ea4cb52c73ed4 to your computer and use it in GitHub Desktop.
Save Lumbe/131ce913ebd97b5c705ea4cb52c73ed4 to your computer and use it in GitHub Desktop.
add js libraries to rails project with yarn

How to add js library to Ruby on Rails project with yarn

1. Install yarn on your system. For Debian/Ubuntu Linux:

$ curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
$ echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
$ sudo apt-get update && sudo apt-get install yarn

2. To add any library, for example jquery, to Ruby on Rails 5.1 application with yarn(from npm) type in terminal:

$ yarn add jquery

This will add jquery dependency to package.json file in root directory and generate yarn.lock file(similar to Gemfile and Gemfile.lock for Ruby gems).

3. Run:

$ yarn              # like 'bundle' for ruby gems

or

$ yarn install      # like 'bundle install' for ruby gems

This will add jquery to /node_modules in the root of rails project.

4. Require jquery in application.js file:

# app/assets/javascripts/application.js
//= require js

That's it.

However! To install datatables.net:

$ yarn add datatables.net
$ yarn

To require library in application.js you must directly specify path to the library location(/node_modules/datatables.net/js/jquery.dataTables). Don't now if it's a bug or feature :)

# app/assets/javascripts/application.js
...
//= require datatables.net/js/jquery.dataTables

This location may be find at /node_modules/_modul_name/package.json - key main.

For datatables.net module it was: "main": "./js/jquery.dataTables.js"

@gsanchezd
Copy link

Any hints in why its necessary to add the path for datatables but not for jquery?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment